Tip:A–D to answerE for explanationV for videoS to reveal answer
What will be the output of the following C program?
#include <stdio.h>
int recur (int n) {
if (n == 0)
return 0;
else
return n + recur (n - 1);
}
int main() {
int result = recur(4);
printf("%d\n", result);
return 0;
}
- A.
10
(Correct Answer) - B.
6
- C.
4
- D.
0
Explanation
In the provided code, the function recur(n) implements a summation sequence. Let's trace the execution stack when recur(4) is called:
recur(4) returns 4+recur(3)
recur(3) returns 3+recur(2)
recur(2) returns 2+recur(1)
recur(1) returns 1+recur(0)
recur(0) hits the base case and returns 0
Now, we substitute the values back up the stack:
result=4+(3+(2+(1+0)))
result=4+3+2+1+0
result=10
Correct Answer: (A) 10