265 views
5 5 votes

What is the output of the following code?

#include <stdio.h>

int fun(int n) {
    static int sum = 0;
    int temp;

    if (n <= 0)
        return sum;

    sum = sum + n;

    temp = fun(n - 2);

    return temp + sum;
}

int main() {
    printf("%d", fun(5));
    return 0;
}

2 Answers

2 2 votes

Here, $\texttt{sum}$ is a static variable.

So, there is only one copy of $\texttt{sum}$, and it keeps its value across recursive calls.

Initially, $\texttt{sum = 0}$.

For $\texttt{fun(5)}$:

$\texttt{sum = 0 + 5 = 5}$, then it calls $\texttt{fun(3)}$.

For $\texttt{fun(3)}$:

$\texttt{sum = 5 + 3 = 8}$, then it calls $\texttt{fun(1)}$.

For $\texttt{fun(1)}$:

$\texttt{sum = 8 + 1 = 9}$, then it calls $\texttt{fun(-1)}$.

For $\texttt{fun(-1)}$, the base condition is true, so it returns $\texttt{sum}$.

So, $\texttt{fun(-1)}$ returns $\texttt{9}$.

Now returning starts.

In $\texttt{fun(1)}$, $\texttt{temp = 9}$ and current $\texttt{sum = 9}$.

So, $\texttt{fun(1)}$ returns $\texttt{9 + 9 = 18}$.

In $\texttt{fun(3)}$, $\texttt{temp = 18}$ and current $\texttt{sum = 9}$.

So, $\texttt{fun(3)}$ returns $\texttt{18 + 9 = 27}$.

In $\texttt{fun(5)}$, $\texttt{temp = 27}$ and current $\texttt{sum = 9}$.

So, $\texttt{fun(5)}$ returns $\texttt{27 + 9 = 36}$.

$\therefore$ Output $:\texttt{36}$

edited by
Answer:
Position:
Show:

Related questions

6 6 votes
3 3 answers
233
233 views
GO Classes asked Jun 16
233 views
What is the output of the following code?#include <stdio.h int fun(int n) { static int step = 1; if (n <= 1) return n; step++; return n + fun(n - step); } int main() { pr...
6 6 votes
3 3 answers
311
311 views
GO Classes asked Jun 16
311 views
What is the output of the following code?#include <stdio.h void fun(int n) { static int x = 0; if (n == 0) return; x++; printf("%d:%d ", n, x); fun(n - 1); printf("%d:%d ...
5 5 votes
4 4 answers
330
330 views
GO Classes asked Jun 16
330 views
What is the output of the following code?#include <stdio.h void g(int n); void f(int n) { if (n <= 0) return; printf("F%d ", n); g(n - 1); printf("f%d ", n); } void g(int...
5 5 votes
3 3 answers
295
295 views
GO Classes asked Jun 16
295 views
What is the output of the following code?#include <stdio.h int fun(int n) { if (n == 0) return 1; return n + fun(n - 1); printf("%d ", n); } int main() { printf("%d", fun...