What is the output of the following ‘C’ language statements? #include…
2023
What is the output of the following ‘C’ language statements? #include <stdio.h> int main() { int a = 10, b = 20, *p1 = &a, *p2 = &b; printf("Before : **p1=%d **p2=%d", *p1, *p2); *p1 = *p1 + *p2; *p2 = *p1 - *p2; *p1 = *p1 - *p2; printf("\nAfter : **p1=%d **p2=%d", *p1, *p2); return 0; }
Attempted by 546 students.
Show answer & explanation
Concept
Two variables x and y can be swapped without using a temporary variable through pure arithmetic on their dereferenced values: setting x = x + y makes x hold the sum of the two original values; then y = x − y subtracts the original y from that sum, leaving y with the original value of x; finally x = x − y subtracts this new y (the original x) from the sum, leaving x with the original value of y. This gives an exact swap using only addition and subtraction — no extra storage is needed — provided the intermediate sum stays within the representable integer range, which holds for the values used here (10 and 20).
Step-by-step application
Before any arithmetic: a = 10, b = 20, p1 points to a, and p2 points to b, so *p1 = 10 and *p2 = 20 — this is the "Before" line the first printf prints.
*p1 = *p1 + *p2 assigns *p1 = 10 + 20 = 30; since p1 points to a, a now holds 30.
*p2 = *p1 - *p2 assigns *p2 = 30 - 20 = 10; b now holds 10.
*p1 = *p1 - *p2 assigns *p1 = 30 - 10 = 20; a now holds 20.
After the three assignments: *p1 = 20 and *p2 = 10 — this is what the second printf prints.
Cross-check
The sum *p1 + *p2 before the assignments (10 + 20 = 30) equals the sum after (20 + 10 = 30): no value was created or lost, confirming the two values were exchanged between a and b rather than altered.
Result
The program prints: Before : **p1=10 **p2=20, then After : **p1=20 **p2=10.