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.
Notice the
;after theforloop. That is the reason why you get only one output. Thestd::coutis executed after the loop exits; it is outside the loop.That is the answer to your first question. Now the second question:
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-pedanticoption with GCC, then it shouldn’t compile if you, by chance, callmain()from your program.