Home > Enterprise >  Follow pattern until negative then reverse using recursion
Follow pattern until negative then reverse using recursion

Time:11-20

Trying to write a program that follows a simple pattern (x-y, x y) as practice with recursion. Essentially taking a number, subtracting the second until reaching a negative value, then adding until reaching the original value. I understand my base case is reaching the original value, and my recursive case to subtract until negative but I can't quite figure out how to turn around and recurse back up to the original value.

void PrintNumPattern(int x, int y){

    cout << x << " ";

        if(x == //Original value//){ 
            cout << endl; 
        } 
        else{
            if(//has been negative//){
                PrintNumPattern(x   y, y); 
                } 
                else{
                     PrintNumPattern(x - y, y); 
                } 
            } 
        }

int main() {
    int num1; 
    int num2;

    cin >> num1;
    cin >> num2;
    PrintNumPattern(num1, num2);

    return 0;
} 

CodePudding user response:

Just print the value twice for each recursive call. You can't really know what the original value was, unless you pass it into the function:

void PrintNumPattern(int x, int y){
    std::cout << x << " ";             // Print "x" first
    if ( x >= 0 ) {                    // If x is positive (or zero?) keep recursing
        PrintNumPattern( x - y, y );   // Recursive call
        std::cout << x << " ";         // When recursive call is done, print the value again
    }
}

With x = 100, and y = 7, output would be:

100 93 86 79 72 65 58 51 44 37 30 23 16 9 2 -5 2 9 16 23 30 37 44 51 58 65 72 79 86 93 100 

CodePudding user response:

The easiest is to add 2 more parameters, 1 for the original x and 1 to syy if x were negative.

void PrintNumPattern(int x, int y,int original,bool was_neg){
...
    if (x==original && was_neg/*if you don't add this it will exit at the first run*/)
...
    if (x<0) {was_neg=true;}
    if (was_neg){
        PrintNumPattern(x   y, y, original,true);
    }else{
        PrintNumPattern(x - y, y, original,false);
    }
 
}
...

//and the call:
`PrintNumPattern(num1, num2,num1,false);`
  •  Tags:  
  • c
  • Related