346 views
6 6 votes

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 ", n, x);
}

int main() {
    fun(3);
    return 0;
}
  1. $\texttt{3:1\ 2:2\ 1:3\ 1:3\ 2:3\ 3:3}$
     
  2. $\texttt{3:1\ 2:2\ 1:3\ 1:1\ 2:2\ 3:3}$
     
  3. $\texttt{1:1\ 2:2\ 3:3\ 3:3\ 2:2\ 1:1}$
     
  4. $\texttt{3:1\ 2:1\ 1:1\ 1:1\ 2:1\ 3:1}$

3 Answers

0 0 votes


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

So, $\texttt{x}$ is shared across all recursive calls.

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

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

So, it prints $\texttt{3:1}$ and calls $\texttt{fun(2)}$.

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

So, it prints $\texttt{2:2}$ and calls $\texttt{fun(1)}$.

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

So, it prints $\texttt{1:3}$ and calls $\texttt{fun(0)}$.

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

Now returning starts.

Since $\texttt{x}$ is static, its current value is still $\texttt{3}$.

So, while returning:

$\texttt{fun(1)}$ prints $\texttt{1:3}$.

$\texttt{fun(2)}$ prints $\texttt{2:3}$.

$\texttt{fun(3)}$ prints $\texttt{3:3}$.

$\therefore$ Complete Output :

$\texttt{3:1\ 2:2\ 1:3\ 1:3\ 2:3\ 3:3}$

Answer: A

• edited by
Answer:
Position:
Show:

Related questions

5 5 votes
2 2 answers
298
298 views
GO Classes asked Jun 16
298 views
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...
6 6 votes
3 3 answers
270
270 views
GO Classes asked Jun 16
270 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...
5 5 votes
4 4 answers
360
360 views
GO Classes asked Jun 16
360 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
326
326 views
GO Classes asked Jun 16
326 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...