278 views
7 7 votes

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)
        return;

    printf("%d ", n);
    f(n - 2);
}

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

3 Answers

0 0 votes

 

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

In $\texttt{f(5)}$, $\texttt{5}$ is printed and then $\texttt{g(4)}$ is called.

In $\texttt{g(4)}$, $\texttt{4}$ is printed and then $\texttt{f(2)}$ is called.

In $\texttt{f(2)}$, $\texttt{2}$ is printed and then $\texttt{g(1)}$ is called.

In $\texttt{g(1)}$, $\texttt{1}$ is printed and then $\texttt{f(-1)}$ is called.

In $\texttt{f(-1)}$, the condition $\texttt{n <= 0}$ is true, so it returns.

Therefore, the output is $\texttt{5\ 4\ 2\ 1}$

Answer: B

Answer:
Position:
Show:

Related questions

7 7 votes
4 4 answers
388
388 views
GO Classes asked Jun 15
388 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
288
288 views
GO Classes asked Jun 15
288 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
290
290 views
GO Classes asked Jun 15
290 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()...
6 6 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); } int main() { fun(3); re...