Problem statement
Write a C program to take two numbers as input from user and stored them in two different variables. Then they interchange the value with each other using third variable.
Program of swapping
1 2 3 4 5 6 7 8 9 10 11 12 |
#include<stdio.h> int main() { int i=0, num1=0, num2=0, temp=0; printf("Enter two numbers\n"); scanf("%d\t %d", &num1, &num2); printf("Before swapping num1 is %d and num2 is %d\n", num1, num2); temp = num1; num1 = num2; num2 = temp; printf("After swapping num1 is %d and num2 is %d", num1, num2); } |
Output
1 2 3 4 |
Enter two numbers 12 76 Before swapping num1 is 12 and num2 is 76 After swapping num1 is 76 and num2 is 12 |
Explanation
Swapping means interchanging the values.
Firstly we take two values from user and stored them into two variables num1 and num2 respectively.
Now we also use third temporary variable temp.
First of all, we store value of num1 into temp variable and value of num2 into num1.
In this way value of the second variable is stored in the first variable.
And lastly, we transfer value of temp into num2.
Therefore we swap the values of two variables using third variable.
Write a program to swap two numbers without using third variable
1 2 3 4 5 6 7 8 9 10 11 12 |
#include<stdio.h> int main() { int num1=0, num2=0; printf("Enter two numbers\t"); scanf("%d\t %d\n", &num1, &num2); printf("Before swap num1=%d and num2=%d\n", num1, num2); num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; printf("After swap anum1=%d and num2=%d", num1, num2); } |
Output
1 2 3 4 |
Enter two numbers 20 50 Before swap num1=10 and num2=20 After swap anum1=20 and num2=10 |
Explanation:
First of all, we take two values i.e, 20 and 50 as input from user and stored them into two variable num1 and num2 respectively.
Now see how these following statements interchange the values,
num1 = num1 + num2
= 20 + 50
num1 = 70
——————————-
num2 = num1 – num2;
= 70 – 50
num2 = 20
——————————-
num1 = num1 – num2;
= 70 – 20
num1 = 50
In this way, we swap the values of two variables without using the third variable.