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; }

20th Nov 2019, 8:47 PM
Preity
Preity - avatar
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.
20th Nov 2019, 9:07 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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
21st Nov 2019, 9:39 AM
Preity
Preity - avatar
+ 1
~ swim ~ Thanks. Now I understand it.
21st Nov 2019, 9:40 AM
Denise Roßberg
Denise Roßberg - avatar
+ 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.
21st Nov 2019, 9:53 AM
Denise Roßberg
Denise Roßberg - avatar
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??
21st Nov 2019, 9:19 AM
Preity
Preity - avatar
0
Preity I can't explain why but i is always 10. You can add a print statement inside the loop.
21st Nov 2019, 9:25 AM
Denise Roßberg
Denise Roßberg - avatar