C Program to Swap Two Numbers
In this example, we will learn to swap two numbers in C programming.
Remainder :
To understand this example, you must have the knowledge of the following C programming topics:
Method 1 : Swap Numbers Using Temporary Variable
#include <stdio.h>
int main(){
int num1, num2, mediator;
printf("Enter two number: ");
scanf("%d %d", &num1, &num2);
mediator = num1;
num1 = num2;
num2 = mediator;
printf("After swapping, First Number is %d\n", num1);
printf("After swapping, Second Number is %d", num2);
return 0;
}
Output
Enter first number: 12
Enter second number: 23
After swapping, First Number is 23
After swapping, Second Number is 12
Working of the above program
- First we declare three integer variables num1, num2 to store user input and swap their values, mediator to use as medium of swaping values.
int num1, num2, mediator;
printf("Enter two number: ");
scanf("%d %d", &num1, &num2);
mediator = num1;
num1 = num2;
num2 = mediator;
printf("After swapping, First Number is %d\n", num1);
printf("After swapping, Second Number is %d", num2);
Method 2 : Swap Numbers Without Using Temporary Variables
#include <stdio.h>
int main() {
int num1, num2;
printf("Enter two number: ");
scanf("%d %d", &num1, &num2);
num1 = num1 - num2;
num2 = num1 + num2;
num2 = num2 - num1;
printf("After swapping, First Number = %d\n", num1);
printf("After swapping, Second Number = %d", num2);
return 0;
}
Output
Enter two numbers : 12 34
After swapping, First Number = 34
After swapping, Second Number = 12
Working of the above program
- First we declare three integer variables num1, num2 to store user input and swap their values, mediator to use as medium of swaping values.
int num1, num2;
printf("Enter two number: ");
scanf("%d %d", &num1, &num2);
num1 = num1 - num2;
num2 = num1 + num2;
num1 = num2 - num1;
printf("After swapping, First Number = %d\n", num1);
printf("After swapping, Second Number = %d", num2);