int main()
{
f1();
f2(2);
f3();
return(0);
}
int f1()
{
return(1);
}
int f2(int X)
{
f3();
if (X==1)
return f1();
else
return (X*f2(X-1));
}
int f3()
{
return(5);
}
Which one of the following options represents the activation tree corresponding to the main function?
A
Step-by-Step Solution
Insight: Trace the execution step-by-step, drawing a new node for every function invocation, especially noting the recursive call in f2.
Exam route:
- main calls f1, f2(2), f3. So main has 3 children: f1, f2, f3.
- f2(2) calls f3, then since 2!=1, it calls f2(1). So f2(2) has 2 children: f3, f2(1).
- f2(1) calls f3, then since 1==1, it calls f1. So f2(1) has 2 children: f3, f1.
- Match this tree structure with the options. Option A matches perfectly.
Learning route:
- Start at main. The code shows sequential calls: f1(), f2(2), f3(). Thus, the main node has three children in order: f1, f2, f3.
- Examine the first f2 invocation, f2(2). Inside f2, it first calls f3(). Then it checks X==1. Since X=2, it goes to the else branch and evaluates X*f2(X-1), which invokes f2(1). Thus, the f2 node (for X=2) has two children: f3 and f2 (for X=1).
- Examine the second f2 invocation, f2(1). Inside this call, it first calls f3(). Then it checks X==1. Since X=1, it evaluates return f1(), invoking f1(). Thus, this second f2 node has two children: f3 and f1.
- The complete activation tree is: main has children [f1, f2, f3]. The first f2 has children [f3, f2]. The second f2 has children [f3, f1].
- Option A depicts exactly this hierarchy. Option B misses the recursive f2 call entirely. Option D incorrectly makes f3, f2, and f1 all direct children of the first f2, ignoring the nesting of the recursive call.