Which one of the choices given below would be printed when the following…

2006

Which one of the choices given below would be printed when the following program is executed?

#include
void swap (int *x, int *y)
{
    static int *temp;
    temp = x;
    x = y;
    y = temp;
}
void printab ()
{
    static int i, a = -3, b = -6;
    i = 0;
    while (i <= 4)
    {
        if ((i++)%2 == 1) continue;
        a = a + i;
        b = b + i;
    }
    swap (&a, &b);
    printf("a =  %d, b = %d\\n", a, b);
}
main()
{
    printab();
    printab();
} 

  1. A.

    a = 0, b = 3

    a = 0, b = 3

  2. B.

    a = 3, b = 0

    a = 12, b = 9

  3. C.

    a = 3, b = 6

    a = 3, b = 6

  4. D.

    a = 6, b = 3

    a = 15, b = 12

Attempted by 121 students.

Show answer & explanation

Correct answer: D

Explanation: a and b are static and initialized once to -3 and -6. They retain their values across calls to printab.

Key detail about the loop:

  • The condition uses (i++)%2, so the test uses the old i and then i is incremented. When the test is false, the code uses the incremented i for the additions.

  • For i starting at 0 the additions performed are when i becomes 1, 3, and 5 (i.e., values 1, 3, 5). Their sum is 9.

Compute values after the first call:

  • a = -3 + (1 + 3 + 5) = -3 + 9 = 6

  • b = -6 + (1 + 3 + 5) = -6 + 9 = 3

About the swap function:

  • The function assigns the pointer parameters to each other (and uses a static pointer), but it does not dereference the pointers to swap the pointed-to values. Therefore a and b remain unchanged by the call.

Second call:

  • a increases by another 9: 6 + 9 = 15

  • b increases by another 9: 3 + 9 = 12

Final output:

a = 6, b = 3

a = 15, b = 12

Explore the full course: Gate Guidance By Sanchit Sir