What is the value returned by the function f given below when n = 100?
What is the value returned by the function f given below when n = 100?
int f(int n)
{ if (n == 0) then return n;
else
return n + f(n – 2);}
Show answerHide answer
Correct answer: (A) 2550
Explanation
The function is recursive and starts with n = 100. It keeps adding the present value to f(n – 2) and stops at n = 0, where it returns 0. So it computes 100 + 98 + ... + 2, an arithmetic series with 50 terms, first term 100 and last term 2. Sum = (n/2)(a + l) = (50/2)(100 + 2) = 2550