📜  门| GATE-CS-2014-(Set-1) |问题 22(1)

📅  最后修改于: 2023-12-03 15:28:43.701000             🧑  作者: Mango

GATE-CS-2014-(Set-1) | Question 22

Problem Statement

Consider the C code fragment given below:

void f(int n)
{
    if(n<=0) return;
    printf("%d",n);
    f(n-2);
    printf("%d",n);
}

What is the output of the following function for input 4?

void main()
{
    f(4);
}
Options

A. 41324
B. 43124
C. 41342
D. 43142

Solution

The function f(int n) prints the integers in the following order for an input of n:

  1. If n is less than or equal to 0, return from the function.
  2. Print n.
  3. Call the function f(n-2).
  4. Print n.

So, if the input is 4, then the order of printing would be:

  1. 4 - Step 2
  2. 2 - Step 2 (from f(2) - Step 3)
  3. 2 - Step 4 (from f(2) - Step 3)
  4. 4 - Step 4 (from f(2) - Step 3)
  5. 1 - Step 2 (from f(1) - Step 3)
  6. 1 - Step 4 (from f(1) - Step 3)
  7. 3 - Step 4 (from f(3) - Step 3)
  8. 3 - Step 2 (from f(3) - Step 3)
  9. 4 - Step 4
  10. 4 - Step 2

Therefore, the output would be 2412434.

Hence, the correct answer is option A.

Code Implementation
void f(int n)
{
    if(n<=0) return;
    printf("%d",n);
    f(n-2);
    printf("%d",n);
}

void main()
{
    f(4);
}