2

I'm getting two problem when I call the recursive function inside a loop. Consider the following sample code:

int fact(int x)
{
    if(x == 1)
        return 1;
    return x*fact(x-1);
}

int main() { 
    int n = 2;
    for(int i = 0; i < n; i++);
        std::cout << fact(4) << std::endl; // 24 ??
    return 0;
}

Problem 1: My expected result for this program is 24 24 (two times 24 to be printer) but the actual result I got only one 24.

Problem 2: What is the reason for the main() function called repetitively even I'm not recursively calling the main function.

It'd be great if anyone give me your thoughts about how to call the recursive function inside the loop for getting multiple output.

1 Answer 1

12
for(int i=0; i < n; i++); <---------------------- notice this
       std::cout << fact(4) << std::endl; // 24 ??

Notice the; after the for loop. That is the reason why you get only one output. The std::cout is executed after the loop exits; it is outside the loop.

That is the answer to your first question. Now the second question:

What is the reason for the main() function called repetitively even I'm not recursively called the main function.

I don't think the code which you've posted has this problem. You must be doing something else in the code which you've not posted, because of which main() is getting called recursively.

Note that calling main() from your code (recursively or otherwise) is forbidden by C++ language specification. So if you compile it with -pedantic option with GCC, then it shouldn't compile if you, by chance, call main() from your program.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.