Skip to content
Official PYQ · 2015

GATE CS 2015 Set 2 Q38 — Arrays, Stacks and Queues

Explain with AI

Consider the C program below

#include <stdio.h>
int *A, stkTop;
int stkFunc (int opcode, int val)
{
    static int size=0, stkTop=0;
    switch (opcode) {
        case -1: size = val; break;
        case 0: if (stkTop < size ) A[stkTop++]=val; break;
        default: if (stkTop) return A[--stkTop];
    }
    return -1;
}
int main()
{
    int B[20]; A=B; stkTop = -1;
    stkFunc (-1, 10);
    stkFunc (0, 5);
    stkFunc (0, 10);
    printf ("%d\n", stkFunc(1, 0)+ stkFunc(1, 0));
}

The value printed by the above program is ________.

View worked solution

Answer: 15

To find the value printed by the program, let us trace the execution step-by-step:

1. Variable Scope and Lifetime

  • The global variable stkTop is shadowed inside the function stkFunc by the local static int stkTop. Therefore, the assignment stkTop = -1 in main() has no effect on the stack operations.
  • The static variables size and stkTop inside stkFunc retain their values across multiple function calls.

2. Step-by-Step Execution

  1. stkFunc(-1, 10);
    • opcode = -1, val = 10.
    • Matches case -1:   ⟹  \implies size = 10.
    • Returns -1.
  2. stkFunc(0, 5);
    • opcode = 0, val = 5.
    • Matches case 0: since stkTop (0) < size (10), A[0] = 5 is assigned, and stkTop is incremented to 1.
    • Returns -1.
  3. stkFunc(0, 10);
    • opcode = 0, val = 10.
    • Matches case 0: since stkTop (1) < size (10), A[1] = 10 is assigned, and stkTop is incremented to 2.
    • Returns -1.
  4. stkFunc(1, 0) + stkFunc(1, 0)
    • For both calls, opcode = 1, which triggers the default case.
    • The default case executes: if (stkTop) return A[--stkTop];
    • First pop operation: stkTop is decremented from 2 to 1, returning A[1] = 10.
    • Second pop operation: stkTop is decremented from 1 to 0, returning A[0] = 5.

The sum of the two returned values is:

10+5=1510 + 5 = 15

Thus, the value printed by the program is 15.

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

Published
Report a correction
Keep exploringMore Arrays, Stacks and Queues questions