[Solved] Why is this recursive function creating an infinite loop? [closed]


First, you are accessing an uninitialized variable. This introduces undefined behaviour into your program; I’d remove this section.

Second, your while-loop runs as long as a > 0, but in the body of the loop, the value of a is never changed. Note that when calling init, parameter a is passed by value, i.e. the value of a is copied; Each instance of init will get it’s own a, and it will never change the value of the caller’s a.

Recursive functions usually are used instead of a loop. Nevertheless, you need an “anchor” to tell the recursion where to stop:

void init(int a)
{
    int j = a;
    cout<<"After initializing: " << j;
    if (a>0) {
       init (a-1);
    }  
}

solved Why is this recursive function creating an infinite loop? [closed]