Open In App
Related Articles

UGC-NET | UGC NET CS 2015 Jun – III | Question 33

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

What is the output of the following recursive function when called with n=5?

C++

int foo(int n) {
    if(n == 0)
      return 1;
    else
      return n * foo(n - 1);
}

                    
(A)

1

(B)

5

(C)

120

(D)

720



Answer: (C)

Explanation:

The given recursive function calculates the factorial of a non-negative integer n.

When the function is called with n=5, the function checks whether n is equal to 0. Since n is not equal to zero, it returns the value of n times the value of the same function called with n-1 as input. This recursive call continues until the base case (n==0) is reached.

The calculation for foo(5) would be: foo(5) = 5 * foo(4) foo(4) = 4 * foo(3) foo(3) = 3 * foo(2) foo(2) = 2 * foo(1) foo(1) = 1 * foo(0) foo(0) = 1

Substituting foo(0) = 1 in foo(1): foo(1) = 1 * 1 = 1 Substituting foo(1) = 1 in foo(2): foo(2) = 2 * 1 = 2 Substituting foo(2) = 2 in foo(3): foo(3) = 3 * 2 = 6 Substituting foo(3) = 6 in foo(4): foo(4) = 4 * 6 = 24 Substituting foo(4) = 24 in foo(5): foo(5) = 5 * 24 = 120

Therefore, the output of the function when called with n=5 is 120, which is option C.



Quiz of this Question
Please comment below if you find anything wrong in the above post

Last Updated : 20 Jun, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads