#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
// swap the values of a and b using two variables
a = a + b;
b = a - b;
a = a - b;
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Explanation
In this program, we first declare two integer variables a and b. Then we ask the user to input two numbers using the scanf() function. We print the original values of a and b using the printf() function.
To swap the values of a and b using two variables, we use the following steps:
- Add a and b and store the result in a: a = a + b;
- Subtract b from a and store the result in b: b = a – b;
- Subtract the original value of b from a and store the result in a: a = a – b;
Finally, we print the swapped values of a and b using the printf() function.