in Algorithms edited by
11,023 views
26 votes
26 votes

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$
in Algorithms edited by
11.0k views

4 Comments

How I can do this? I mean which offline ide you are using and how to check the call stack after execution?
1
1
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.
1
1
starting point is fun(95)
1
1

6 Answers

39 votes
39 votes
Best answer
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$
edited by

4 Comments

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
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;
}
0
0

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

0
0

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$

0
0
6 votes
6 votes
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.

2 Comments

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

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

Equivalent function.
edited by
1 vote
1 vote

I think the answer is 91.

1 comment

Thanks Ahsanul
0
0
Answer:

Related questions