![]() |
VOOZH | about |
Question 1 : Predict the output of the following program. What does the following fun2() do in general?
Answer: For a positive n, fun2(n) prints the values of n, 2n, 4n, 8n ... while the value is smaller than LIMIT. After printing values in increasing order, it prints same numbers again in reverse order. For example fun2(100) prints 100, 200, 400, 800, 800, 400, 200, 100.
If n is negative, the function is returned immediately.
Question 2 : Predict the output of the following program. What does the following fun() do in general?
Answer: fun() returns the maximum value in the input array a[] of size n.
Question 3 : Predict the output of the following program. What does the following fun() do in general?
Answer: If n is odd, then return n, else returns (n-1). Eg., for n = 12, you get 11 and for n = 11 you get 11. The statement "return i++;" returns the value of i only as it is a post-increment.
Question 4 : Predict the output of the following program. What does the following fun() do in general?
The program calculates n-th Fibonacci Number. The statement t = fun ( n-1, fp ) gives the (n-1)th Fibonacci number and *fp is used to store the (n-2)th Fibonacci Number. The initial value of *fp (which is 15 in the above program) doesn't matter. The following recursion tree shows all steps from 1 to 10, for the execution of fun(5, &x).
(1) fun(5, fp)
/ \
(2) fun(4, fp) (8) t = 3, f = 5, *fp = 3
/ \
(3) fun(3, fp) (7) t = 2, f = 3, *fp = 2
/ \
(4) fun(2, fp) (6) t = 1, f = 2, *fp = 1
/
(5) *fp = 1
Question 5 : Predict the output of the following program.
Answer: The function fun2() is a recursive implementation of Selection Sort.
Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above.