Reputation: 53
Why is Hi
being printed 4 times. It will just be executed once before the function finally returns the complete value.
#include <stdio.h>
int k = 0;
int factorial (unsigned int i) {
if (i <= 1) {
return 1;
} else {
k = i * factorial(i - 1);
}
printf("hi"); // Why is Hi being printed 4 times.
return k;
}
int main() {
int i = 5;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
Upvotes: 0
Views: 77
Reputation: 1177
Your printf
's are probably getting queued as the function is trying to call itself.
Let's examine it iteration by iteration -
i = 5
Iteration 1:
k = 5 * factorial(4);
Iteration 2:
k = 4 * factorial(3);
Iteration 3:
k = 3 * factorial(2);
Iteration 4:
k = 2 * factorial(1);
At this point, factorial(1)
actually returns 1. Note that printf
line is not reached in case.
Now, this value is fed to k
in iteration 4 and its returned back to its caller while doing a printf
.
The same happens in iteration 3, it receives a value in k
and returns it to its caller i.e. iteration 2 while doing another printf
Now, iteration 2 receives a value for k
and returns it to its caller i.e. iteration 1 while doing yet another printf
(3rd time!)
Finally, iteration 1 receives a value for k
and returns it, and along with that it does a final printf
(Total 4)
I hope that explains your issue! For ref: http://ideone.com/VgIwKX
Upvotes: 1
Reputation: 13934
Because your code gets executed in this fashion:
k = 5 * factorial(5 - 1);
k = 4 * factorial(4 - 1);
k = 3 * factorial(3 - 1);
k = 2 * factorial(2 - 1);
return 1;
printf("hi");
printf("hi");
printf("hi");
printf("hi");
Upvotes: 5
Reputation: 521
The function factorial()
is called five times:
main()
method andAll the times that the i
parameter is > 1
the function prints "hi"
.
Even if you are using the recursion, the execution if a program (or function) ends when the end point is reached, for a function the end point is the return
statement.
Upvotes: 0