Reputation: 1
I ran this code on C and in Java and I got 65 and 55 respectively. I cannot fathom how C can get 65. Please help.
int recur(int count)
{
if(count==10)
return count;
else
return (count+recur(++count));
}
void main()
{
printf("%d\n",recur(0));
}
Upvotes: 0
Views: 59
Reputation: 65506
Rewriting the code and testing on codepad with some debug statements shows what's happening. I encourage you to take this approach with running code to see what's happening.
int recur(int count)
{
int ret;
if(count==10)
ret = count;
else {
printf("Count Before = %d\n", count);
ret = (count +recur(++count));
}
printf("Count after = %d\n", ret);
return ret;
}
void main()
{
printf("%d\n",recur(0));
}
Running it gives this
Count Before = 0
Count Before = 1
Count Before = 2
Count Before = 3
Count Before = 4
Count Before = 5
Count Before = 6
Count Before = 7
Count Before = 8
Count Before = 9
Count after = 10
Count after = 20
Count after = 29
Count after = 37
Count after = 44
Count after = 50
Count after = 55
Count after = 59
Count after = 62
Count after = 64
Count after = 65
65
So you can see that recurse up to 10 first , then add 10, then 9 then 8 etc...
Changing it to i = (count + recur(count + 1))
gives
Count Before = 0
Count Before = 1
Count Before = 2
Count Before = 3
Count Before = 4
Count Before = 5
Count Before = 6
Count Before = 7
Count Before = 8
Count Before = 9
Count after = 10
Count after = 19
Count after = 27
Count after = 34
Count after = 40
Count after = 45
Count after = 49
Count after = 52
Count after = 54
Count after = 55
Count after = 55
55
But now the 10 level of nesting is only reached but added amount is still at 9.
Ie. the pre increment means you're adding an extra 10.
Upvotes: 1
Reputation: 4463
return (count+recur(++count));
Is Undefined Behaviour. On different compilers you may have different results, even same compiler with different compilation options may result to different output.
Upvotes: 1