233 views

2 Answers

0 0 votes

The function call is $\texttt{sum(5)}$.

The function returns $\texttt{n + sum(n - 1)}$ until $\texttt{n == 1}$.

So,



$\texttt{sum(5) = 5 + sum(4)}$

$\texttt{sum(4) = 4 + sum(3)}$

$\texttt{sum(3) = 3 + sum(2)}$

$\texttt{sum(2) = 2 + sum(1)}$

Base case:

$\texttt{sum(1) = 1}$

Now substitute back:

$\texttt{sum(2) = 2 + 1 = 3}$

$\texttt{sum(3) = 3 + 3 = 6}$

$\texttt{sum(4) = 4 + 6 = 10}$

$\texttt{sum(5) = 5 + 10 = 15}$

Therefore, the output is $\boxed{\texttt{15}}$

• edited by
Answer:
Position:
Show:

Related questions

6 6 votes
2 2 answers
263
263 views
GO Classes asked Jun 13
263 views
What is the output of the following code?#include <stdio.h int fun(int n) { static int count = 0; if (n == 0) return count; count = count + n; return fun(n - 1); } int ma...
5 5 votes
2 2 answers
220
220 views
GO Classes asked Jun 13
220 views
What is the output of the following code?#include <stdio.h int fact(int n) { if (n == 0) return 1; return n * fact(n - 1); } int main() { printf("%d", fact(4)); return 0;...
3 3 votes
2 2 answers
205
205 views
GO Classes asked Jun 13
205 views
What is the output of the following code?#include <stdio.h void fun(int n) { if (n == 0) return; fun(n - 1); printf("%d ", n); } int main() { fun(4); return 0; }$\texttt{...
4 4 votes
2 2 answers
235
235 views
GO Classes asked Jun 13
235 views
What is the output of the following code?#include <stdio.h void fun(int n) { if (n == 0) return; printf("%d ", n); fun(n - 1); } int main() { fun(4); return 0; }$\texttt{...