In this video tutorial we shall learn how to swap two integer numbers without using a temporary variable and by simply making use of addition and subtraction.
Related Read:
Basic Arithmetic Operations In C
Swap 2 Numbers Using a Temporary Variable: C
Swap 2 Numbers Without Using a Temporary Variable: C
- #include < stdio.h >
- int main()
- {
- int a, b;
- printf("Enter 2 integer numbers for, a and b\n");
- scanf("%d %d", &a, &b);
- printf("You entered a = %d and b = %d\n", a ,b);
- a = a + b;
- b = a - b;
- a = a - b;
- printf("After swapping a = %d, b = %d\n", a, b);
- return 0;
- }
Output:
Enter 2 integer numbers, for a and b
30
20
You entered a = 30 and b = 20
After swapping a = 20, b = 30
Scanf(): For user input
In above c program we are asking user to enter the values for variable a and b. You can know more about scanf() method/function in this video tutorial: Using Scanf in C Program
Swap 2 numbers using only Addition and Subtraction: C
Swapping 2 Numbers In C using only addition and subtraction: Logic
In our above program we are asking user to enter integer value for a and b.
If the user enters 30 and 20 for a and b respectively. Then our program executes below logic to swap the values of variable a and b.
Step 1: Add values of a and b and store it in variable a.
i.e.,
a = a + b;
50 = 30 + 20;
So a = 50;
Step 2: Now subtract value of b from value of a and store it in variable b.
i.e.,
b = a – b;
30= 50 – 20; (value of a = 50 according to Step 1)
So value of variable b is now 30.
Step 3: Now subtract value of b from value of a and store it in variable a.
i.e.,
a = a – b;
20= 50 – 30; (Value of a = 50 from Step 1, and Value of b = 30 from Step 2)
Finally value of a = 20(from step 3) and value of b = 30(from step 2).
This is how we swap the value of variable a and b by just making use of addition and subtraction in C programming language.
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert