Machine-translated by Google. Questions are authored in English.
Top

Discussion

Consider the following program:

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.Activation tree: main calls f1, f2 and f3; f2 calls f3 and f2; the inner f2 calls f3 and f1
  • B.Activation tree: main calls f1, f2 and f3; f2 calls f3 and f1
  • C.Activation tree: main calls f1, which calls f2, which calls f3 and f1
  • D.Activation tree: main calls f1, f2 and f3; f2 calls f3, f2 and f1

Answer: A

The activation tree is (A).

An activation tree has one node per call, with each call's children in the order it makes them. Trace the program:

  • main calls f1(), then f2(2), then f3(): three children, in that order.
  • f2(2) first calls f3(); since X = 2 it then calls f2(1).
  • f2(1) first calls f3(); since X = 1 it then calls f1() and returns.

So main has children f1, f2, f3; that f2 has children f3 and f2; and the inner f2 has children f3 and f1. This is tree (A).

(B) stops after one level of f2 and misses the recursive call f2(1). (C) makes f2 a child of f1, but f1 calls nothing. (D) puts f3, f2 and f1 all under the first f2, when f1 is called by the inner f2(1).

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.