This program shows how to swap the values of two variables without using a temporary (third) variable, using arithmetic operators.
C Program
#include <stdio.h>
int main() {
int a, b;
printf("Enter value of a: ");
scanf("%d", &a);
printf("Enter value of b: ");
scanf("%d", &b);
printf("\nBefore swapping: a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Explanation
a = a + bstores the sum of both numbers ina.b = a - bsubtracts the originalbfrom the sum, leaving the original value ofainb.a = a - bsubtracts the newb(which is the originala) from the sum, leaving the original value ofbina.
No extra memory is used for a temporary variable — the swap happens purely through arithmetic. (An alternative approach uses the XOR bitwise operator instead of addition/subtraction.)
Sample Output
Enter value of a: 5
Enter value of b: 10
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5