In this program, we will see how we can swap the values of two variables in C. To understand this program, you should
know about the following topics in C:
- Data types
- Operators
- Input / Output
We shall take two approaches, one by using a third variable and other by not using any other variable.
Program 1: By using a temporary third variable
#include <stdio.h>
int main()
{
int x, y, temp;
printf("Enter first number ");
scanf("%d", &x);
printf("\nEnter second number ");
scanf("%d", &y);
temp = x;
x = y;
y = temp;
printf("\nThe values after Swapping: x = %d, y = %d", x, y);
return 0;
}
Explanation of the program
- First of all we have declared three integer type variables named x, y, and temp. x and y will be used to store the two input numbers while the variable temp will be used to swap the values of x and y.
- Then using the printf and scanf functions, two inputs are taken from the user. The first input will be stored in x and tghe second will be stored in y.
- Then temp variable will be assigned the value of x, x will be assigned the value of y and y will be assigned the value of temp. Doing this, the values of x and y will be swapped.
- Finally, the new values of x and y as the output message will be displayed using the printf function.
Program 2: Without using any third variable
#include <stdio.h>
int main()
{
int x, y;
printf("Enter first number ");
scanf("%d", &x);
printf("\nEnter second number ");
scanf("%d", &y);
a = a - b
b = a + b
a = b - a
printf("\nThe values after Swapping: x = %d, y = %d", x, y);
return 0;
}