Skip to content
Official PYQ · 2005

GATE CS 2005 Q31 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the following C-program:

void foo (int n, int sum) {
    int k = 0, j = 0;
    if (n == 0) return;
    k = n % 10; j = n/10;
    sum = sum + k;
    foo (j, sum);
    printf ("%d,",k);
}

int main() {
    int a = 2048, sum = 0;
    foo(a, sum);
    printf("%d\n", sum);
}

What does the above program print?

Choose one option
View worked solution

Answer: D

To find the output of the program, we trace the execution step-by-step:

  1. Pass-by-Value Behavior: In C, arguments are passed by value. The variable sum in main() is passed to foo(). Any modifications to sum inside foo() are local to the activation records of foo() and do not affect the variable sum in main(). Thus, the final printf("%d\n", sum) in main() will print 0.
  2. Tracing the Recursion:
    • foo(2048, 0): k=8k = 8, j=204j = 204, local sum=8sum = 8. Calls foo(204, 8). Prints 88 after returning.
    • foo(204, 8): k=4k = 4, j=20j = 20, local sum=12sum = 12. Calls foo(20, 12). Prints 44 after returning.
    • foo(20, 12): k=0k = 0, j=2j = 2, local sum=12sum = 12. Calls foo(2, 12). Prints 00 after returning.
    • foo(2, 12): k=2k = 2, j=0j = 0, local sum=14sum = 14. Calls foo(0, 14). Prints 22 after returning.
    • foo(0, 14): Base case reached (n==0n == 0), returns immediately.

As the recursion unwinds, the printf statements execute in reverse order of the calls (Last-In, First-Out):

  • foo(2, 12) prints 2,
  • foo(20, 12) prints 0,
  • foo(204, 8) prints 4,
  • foo(2048, 0) prints 8,

Finally, main() prints the original value of sum, which is 0. Thus, the complete output is 2,0,4,8,0.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions