0
Can anyone explain this code snippet too why 50 is the answer?
#include <stdio.h> void find(int x){ static int i = 10, y = 0; y = y+i; for(i;i>0;i=i-10){ if (x!=0) find(x-1); else printf("%d",y); } } int main() { find(4); return 0; }
8 Réponses
+ 4
It is a recursive method. Recursion means that this method calls itself.
find(4):
i = 10
y = 10
x = 4
x != 0 -> call find(3)
find(3):
i = 10
y = 20
x = 3
x != 0 -> call find(2)
find(2) -> y gets 30
find(1) -> y gets 40
find(0) -> y gets 50 -> x == 0
-> print y
I am only wondering about the loop. It does nothing with i and I think the code would also work without this loop.
+ 1
#include <stdio.h>
void find(int x){
static int i = 10, y = 0;
y = y+i;
for(i;i>0;i=i-10){
if (x!=0)
find(x-1);
else
printf("%d",y);
printf("\n%d", i);
}
}
int main() {
find(4);
return 0;
}
When I print the value of I inside the function it will give 10, 0, -10, -20, -30
+ 1
~ swim ~ Thanks. Now I understand it.
+ 1
for(i;i>0;i=i-10){
printf("\n%d", i); <-- here
if (x!=0)
find(x-1);
else
printf("%d",y);
}
My fault. I mean at the beginning of the loop before you call the function again.
0
Denise Roßberg
Don't u think I value should change to 10,0,-10,-20.. because of static i. Does static doesn't affect it??
0
Preity
I can't explain why but i is always 10. You can add a print statement inside the loop.