int bar(int val) {
int x = 0;
while(val > 0) {
x= x + bar(val-1);
}
return val;
}
bar() is a recursive function which is calling itself inside a while loop.
so at first Bar(3) will go inside while loop (3>0) and will call Bar(2) which will further call Bar(1) which will also go in while loop
While(1>0){
x= x + bar(1-1);
}
hence it will call bar(0) and return 0 as it will no go in while loop, but after returning in Bar(1) while loop it will keep on the loop
While(1>0){
x= x + bar(1-1);
}
as it will be true forever.
So as mentioned in the best answer of the above question:
- bar(3) will call bar(2)
- bar(2) will call bar(1)
- bar(1) will call bar(0)--------------- Here bar(0) return 0
- bar(1) will call bar(0)
- bar(1) will call bar(0)
This will be an infinite loop