348 views
6 6 votes

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);
    return 0;
}
  1. $\texttt{3\ 2\ 1\ 1\ 2\ 3}$
     
  2. $\texttt{1\ 2\ 3\ 3\ 2\ 1}$
     
  3. $\texttt{3\ 2\ 1}$
     
  4. $\texttt{1\ 2\ 3}$

4 Answers

0 0 votes


The function call is $\texttt{fun(3)}$.

In this function, one $\texttt{printf}$ is before the recursive call and one $\texttt{printf}$ is after the recursive call.

The first $\texttt{printf}$ runs while going down in recursion.

So, it prints:

$\texttt{3\ 2\ 1}$

Then $\texttt{fun(0)}$ is called, and the base condition becomes true.

Now the function calls start returning.

The second $\texttt{printf}$ runs while returning from recursion.

So, it prints:

$\texttt{1\ 2\ 3}$

The complete output is $\texttt{3\ 2\ 1\ 1\ 2\ 3}$

Answer: A

Answer:
Position:
Show:

Related questions

7 7 votes
4 4 answers
378
378 views
GO Classes asked Jun 15
378 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
266
266 views
GO Classes asked Jun 15
266 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...
7 7 votes
3 3 answers
276
276 views
GO Classes asked Jun 15
276 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...
6 6 votes
3 3 answers
272
272 views
GO Classes asked Jun 15
272 views
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()...