edited by
25,326 views
85 votes
85 votes

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

#include <stdio.h>
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 = 0, b = 3$
    $a = 0, b = 3$
  2. $a = 3, b = 0$
    $a = 12, b = 9$
  3. $a = 3, b = 6$
    $a = 3, b = 6$
  4. $a = 6, b = 3$
    $a = 15, b = 12$
edited by

6 Answers

3 votes
3 votes
answer should be:

a =  6, b = 3
a =  15, b = 12

i.e option D
0 votes
0 votes

the given code can be simplified as the code below without changing its meaning and output.

#include <stdio.h>

/*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)
    {
        //we have to increment i irrespective of the number being odd or even
        if (i % 2 == 1) //if i is odd
        {

            i++; // i is incremented here when it is odd
            continue;
        }

        
        i++; //i is incremented here when it is even
        a = a + i;
        b = b + i;
    }



    //we can remove the swap function since it only swaps the pointers to a,b and has no effect on a,b values themselves.
    //swap(&a, &b);
    printf("a =  %d, b = %d\n", a, b);
}
int main()
{
    printab();
    printab();
    return 0;
}

 

Answer:

Related questions