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:
- Initialization:
In
main(), three local variables are initialized:a = 4,b = 5,c = 6 - Function Call
f1(a, b):Since C uses call-by-value, the values of
aandbare copied into the local parameters off1. Any swap operation performed insidef1only affects its local variables and has no effect on the variables inmain().Thus, after
f1(a, b)executes, the variables inmain()remain unchanged:a = 4,b = 5,c = 6 - Function Call
f2(&b, &c):Here, the addresses of
bandcfrommain()are passed tof2. Insidef2, the values at these addresses are swapped using pointers (call-by-reference simulation).- The value of
binmain()becomes6. - The value of
cinmain()becomes5.
After
f2executes, the variables inmain()are:a = 4,b = 6,c = 5 - The value of
- Print Statement:
The program prints the value of the expression
c - a - b:
Therefore, the output of the program is -5.
Free practice · Your answers on this page are not saved.
