in Programming in C retagged by
573 views
4 votes
4 votes

What will be the output printed by $\text{mystery}3(6)$?

void mystery3(int n) {
    if (n == 0 || n == 1) return;
    mystery3(n-2);
    printf("%d", n);
    mystery3(n-1);
}

 

in Programming in C retagged by
573 views

3 Answers

5 votes
5 votes

Here, => means prints.

mystery3(0) => null

mystery3(1) => null

mystery3(2) => mystery3(0) 2 mystery3(1) => 2

mystery3(3) => mystery3(1) 3 mystery3(2) => 32

mystery3(4) => mystery3(2) 4 mystery3(3) => 2432

mystery3(5) => mystery3(3) 5 mystery3(4) => 3252432

mystery3(6) => mystery3(4) 6 mystery3(5) => 243263252432 (answer)

2 votes
2 votes

Answer is 243263252432

Let the function mystery3() be represented as m() for ease. And printf() be represented as p().

Then we create a recursion tree (as shown).

  • For right side of the tree we can reuse the output produced by the same function calls. Like 2432 is produced by mystery3(4)
  • The function mystery3() simply returns when n=0 and when n=1

0 votes
0 votes
Assuming Mystery3() function as M and printf function as P .

Asterisk is made to reuse the value of function without making extra tree.
Answer:

Related questions