Skip to content
Official PYQ · 2015

GATE CS 2015 Set 1 Q1 — Programming in C

Explain with AI

The output of the following C program is_____________.

void f1 ( int a, int b)  {  
                int c; 
                c = a; a = b;
                 b = c;  
}   
void f2 ( int * a, int * b) {   
               int c; 
               c = * a; *a = *b; *b = c; 
} 
int main () { 
        int a = 4, b = 5, c = 6; 
        f1 ( a, b); 
        f2 (&b, &c); 
        printf ("%d", c - a - b);  
 }
View worked solution

Answer: -5

To find the output of the program, let's trace the execution step-by-step starting from the main() function:

  1. Initialization:

    In main(), three local variables are initialized:

    a = 4, b = 5, c = 6

  2. Function Call f1(a, b):

    Since C uses call-by-value, the values of a and b are copied into the local parameters of f1. Any swap operation performed inside f1 only affects its local variables and has no effect on the variables in main().

    Thus, after f1(a, b) executes, the variables in main() remain unchanged:

    a = 4, b = 5, c = 6

  3. Function Call f2(&b, &c):

    Here, the addresses of b and c from main() are passed to f2. Inside f2, the values at these addresses are swapped using pointers (call-by-reference simulation).

    • The value of b in main() becomes 6.
    • The value of c in main() becomes 5.

    After f2 executes, the variables in main() are:

    a = 4, b = 6, c = 5

  4. Print Statement:

    The program prints the value of the expression c - a - b:

    c−a−b=5−4−6=1−6=−5c - a - b = 5 - 4 - 6 = 1 - 6 = -5

Therefore, the output of the program is -5.

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

Published
Report a correction
Keep exploringMore Programming in C questions