in Programming in C
736 views
2 votes
2 votes

https://gateoverflow.in/118319/gate2017-1-36

what is the logic of bar() function please help

in Programming in C
by
736 views

1 Answer

1 vote
1 vote
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:

  1.  bar(3) will call bar(2)
  2. bar(2) will call bar(1)
  3. bar(1) will call bar(0)--------------- Here bar(0) return 0 
  4. bar(1) will call bar(0)
  5. bar(1) will call bar(0)

This will be an infinite loop

Related questions