In this video tutorial we shall learn how to swap two integer numbers without using a temporary variable and by simply making use of multiplication and division.
Related Read:
Basic Arithmetic Operations In C
Swap 2 Numbers Using a Temporary Variable: C
Swap 2 Numbers Without Using a Temporary Variable: C
Swap 2 numbers using Addition and Subtraction: C
#include < stdio.h > int main() { int a, b; printf("Enter 2 integer numbers\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 and b = %d\n", a ,b); return 0; }
Output:
Enter 2 integer numbers
3
5
You entered a = 3 and b = 5
After swapping a = 5 and b = 3
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 Multiplication and Division: C
In our above program we are asking user to enter integer value for a and b.
If the user enters 10 and 5 for a and b respectively. Then our program executes below logic to swap the values of variable a and b.
Step 1: Multiply values of a and b and store it in variable a.
i.e.,
a = a * b;
50= 10 * 5;
So a = 50;
Step 2: Now divide value of b from value of a and store it in variable b.
i.e.,
b = a / b;
10= 50 / 5; (value of a = 50 according to Step 1)
So value of variable b is now 10.
Step 3: Now divide value of b from value of a and store it in variable a.
i.e.,
a = a / b;
5= 50 / 10; (Value of a = 50 from Step 1, and Value of b = 10 from Step 2)
Now the value of a = 5;
Finally value of a = 5(from step 3) and value of b = 10(from step 2).
This is how we swap the value of variable a and b by just making use of multiplication and division in C programming language.
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert