11,023 views

What value would the following function return for the input $x=95$?

Function fun (x:integer):integer;
Begin
If x > 100 then fun = x – 10
Else fun = fun(fun (x+11))
End;
1. $89$
2. $90$
3. $91$
4. $92$

How I can do this? I mean which offline ide you are using and how to check the call stack after execution?
He is using code blocks. You can do it in any IDE. Most of them have a debugging feature where you can check the call stack.
starting point is fun(95)

Value returned by $\text{fun}(95) = \text{fun}(\text{fun}(106))$
$\qquad\qquad= \text{fun}(96)$
$\qquad\qquad= \text{fun}(\text{fun}(107))$
$\qquad\qquad= \text{fun}(97)$
$\qquad\qquad= \text{fun}(\text{fun}(108))$
$\qquad\qquad= \text{fun}(98)$
$\qquad\qquad = \text{fun}(\text{fun}(109))$
$\qquad\qquad= \text{fun}(99)$
$\qquad\qquad= \text{fun}(\text{fun}(110))$
$\qquad\qquad= \text{fun}(100)$
$\qquad\qquad= \text{fun}(\text{fun}(111))$
$\qquad\qquad= \text{fun}(101) = 91.$

Correct Answer: $C$

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include using namespace std; int ans; int fun(int no){ if(no > 100){ ans = no - 10; // this is the terminating condition return no-10; } else{ return fun(fun(no+11)); } } int main() { fun(95); cout << ans << "\n"; return 0; }

@neel19 how after 91 the fucntion is not calling fun(102) ?? can u plz elaborate it

If you see the 3rd last step, we have fun(100). The code says :-

If x > 100 then fun = x – 10
Else fun = fun(fun (x+11))

Now fun(100) = fun(fun(111)) // Since 100 is not > 100.

= fun(101) // since 111 > 100

now this is unlike the other terms which were < 100, so we need to add 11.

Here 101 > 100, thus we again subtract 10 from 101

→ fun = 101-10 = $91$

Yes 91 is correct.

step 1: when fun=111 -> fun(fun(111))

step 2:  fun=101 ->fun(101)

step 3:As 101>100 fun=fun -10 =101-10=91

step 4: as there is no fun function call remaining ,it will exit.
by

how can we understand this is stop codition.
Because when value is 111, there are no further function call. Just the return.
It might help.

int fun(int x)
{
if(x>100)
return (x-10);
else
return fun(fun(x+11));
}

Equivalent function.

Thanks Ahsanul

1
5,608 views
2
4,122 views
3
9,524 views