253 views
6 6 votes

What is the output of the following code?

#include <stdio.h>

int fun(int n) {
    static int x = 0;
    int y;

    if (n == 0)
        return 0;

    x++;
    y = fun(n - 1);

    return y + x;
}

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

3 Answers

0 0 votes

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

A static variable is initialized only once and keeps its value across recursive calls.

 


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

For $\texttt{fun(3)}$, $\texttt{x++}$ makes $\texttt{x = 1}$, then it calls $\texttt{fun(2)}$.

For $\texttt{fun(2)}$, $\texttt{x++}$ makes $\texttt{x = 2}$, then it calls $\texttt{fun(1)}$.

For $\texttt{fun(1)}$, $\texttt{x++}$ makes $\texttt{x = 3}$, then it calls $\texttt{fun(0)}$.

For $\texttt{fun(0)}$, the base condition becomes true and it returns $\texttt{0}$.

Now returning starts.

In $\texttt{fun(1)}$, $\texttt{y = 0}$ and current $\texttt{x = 3}$.

So, it returns $\texttt{0 + 3 = 3}$.

In $\texttt{fun(2)}$, $\texttt{y = 3}$ and current $\texttt{x = 3}$.

So, it returns $\texttt{3 + 3 = 6}$.

In $\texttt{fun(3)}$, $\texttt{y = 6}$ and current $\texttt{x = 3}$.

So, it returns $\texttt{6 + 3 = 9}$.

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

edited by
Answer:
Position:
Show:

Related questions

7 7 votes
3 3 answers
264
264 views
GO Classes asked Jun 15
264 views
What happens when the following code is executed?#include <stdio.h void fun(int n) { if (n == 0) return; printf("%d ", n); fun(n ); } int main() { fun(3); return 0; }$\te...
7 7 votes
4 4 answers
365
365 views
GO Classes asked Jun 15
365 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); printf("%d ", n); fun(n - 2); } int main() ...
7 7 votes
3 3 answers
246
246 views
GO Classes asked Jun 15
246 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("%d ", n); g(n - 1); } void g(int n) { if (n <= 0) re...
6 6 votes
4 4 answers
333
333 views
GO Classes asked Jun 15
333 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); printf("%d ", n); } int main() { fun(3); re...