Originally posted by quzah
Not quite. The issue I believe is to explain what it is doing, and how to produce an interative example that does the same thing. The two examples are not identical. The first does the work 30x for each time the function is called. The second does not. This is actually a huge difference.
Think if we pass it the number 10.
1 call with the value of 10.
30 calls with the value of 9.
30 x 30 calls of the value 8.
30 x 30 x 30 calls of the value 7.
See where I'm going with this? This is a huge difference as far as your CPU is concerned. Imagine if we had passed it a big number.
Quzah.
No it doesnt
The second loop operatates just once, return breaks the loop, so it is always a loop of length 1.
It can be verfied by adding a printf call at the point of entry - so that printf is called every time rec is called. Even the original function involves n+1 function calls for a positive input n.
Code:
#include <stdio.h>
void rec(int depth)
{
int i;
printf("depth=%d\n",depth);
if (depth==0)
return;
for(i=0;i<30;i++)
return rec(depth-1);
}
int main(void)
{
rec(10);
return 0;
}
Output
Code:
depth=10
depth=9
depth=8
depth=7
depth=6
depth=5
depth=4
depth=3
depth=2
depth=1
depth=0