Home > other >  does two recursive calls work simultaneously or one after the other?
does two recursive calls work simultaneously or one after the other?

Time:01-30

so I was testing the recursive function , that is , will the function at first recursion , let the recursion complete and then proceed or will it simply initialize the recursion and proceed on , that is will both the recursive calls print numbers simultaneously or first it will print num to 1 and then it will print num to 100 ; anyway , my compiler is just outputing 32 infinitely when i give num as 23 ;

void print(int num){
   if(num == 1 || num == 100){
        return;
    }
    std::cout << num ;
    print(num-1);
    std::cout << std::endl;
    print(num 1);

    return;
}

CodePudding user response:

That's because when you reach num == 2, what happens is that you call print(1) and stop the recursion, so you go newline and then call print(3) which prints 32 and then stop the recursion but then it will call again print(3) at some point.

Any recursive algorithm must get nearer to the end of the recursion in the recursive case, this is not what happens because with num as an argument you end up calling print(num-1) and print(num 1) thus you go back further from the end, so recursion never ends.

CodePudding user response:

What you're basically doing here is flooding the stack with print() calls, that is your first call to the print function print(num-1) is going to get called recursively untill one of the stop conditions is met. The stopping condition is sometimes met but since you're doing 1 and -1, that is calling the function two times in the same context with no extra checks, it will create a ping pong of infinitely recursive loops, thus resulting in a stack overflow

What you're seeing as '2' and '3' are the last prints of the function calls before it gets to the infinitely recursive ping pong

Watch out, any input given that is not between 1 and 100 will make your function get called infinitely

  •  Tags:  
  • Related