Question
Consider the following program:
int main() int f1() int f2(int X) int f3()
{ { { {
f1(); return(1); f3(); return(5);
f2(2); } if (X==1) }
f3(); return f1();
return(0); else
} return (X*f2(X-1));
}
Which one of the following options represents the activation tree corresponding to the main function?
Official answer and solution
- Official answer
- A
- From
- Official GATE 2023 answer key
Solution
Trace the call hierarchy of function activations starting from main().
main()sequentially calls:f1()f2(2)f3()
- Inside
f2(2):- It calls
f3(). - Since , it executes the
elsebranch:return (X * f2(X-1)), invokingf2(1).
- It calls
- Inside
f2(1):- It calls
f3(). - Since , it executes the
ifbranch:return f1(), invokingf1().
- It calls
- Therefore, the activation tree has
mainat the root with three child branches (f1,f2(2),f3). Underf2(2), there are childrenf3andf2(1). Underf2(1), there are childrenf3andf1. This corresponds exactly to Tree (A).
Final answer
Option (A)
Common trap
Overlooking that f2 calls f3 unconditionally at the very beginning of its body on each invocation.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2023 Computer Science and Information Technology (CS)
- Question
- 36 of 65
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.