Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

# C program to swap two numbers using 2 variables

``````#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:

1. Add a and b and store the result in a: a = a + b;
2. Subtract b from a and store the result in b: b = a – b;
3. 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.