C Program to Swap Two Numbers Without Using Third Variable
What is Swapping?
Generally, the meaning of swapping is to interchange something or change the position of the variables.
For Example: Consider two variables A and B.The value of A is 5 and the value of B is 10 so after swapping the value of a will become 10 and the value of B will become 5.
Algorithm:
1 Step: START.
2 Step: Declare the Variables A, B with values.
3 Step: Declare the temp variable.
4 Step: Logic: temp=A; A=B; and B=temp;
5 Step: Print the values.
6 Step: STOP.
There are different methods to do swapping of two numbers we will see it one by one.
1. Swapping of two numbers Using third Variable
In this program, we will use a third variable temp to store the values of A and B temporarily.
Logic: The idea of using the third variable is very simple.First store the value of A in a temp variable and store the value of B in A.After storing the value of B in A then store the value of temp variable in B.
Thus the two numbers are swapped.
Output:

2. Swapping of two numbers Without Using Third Variable
In the above program, we used the third variable temp to store the values of A and B temporarily. But, in this program, we will not use a temporary variable.
Output:

Logic:
In the first variable, we are storing the sum of both the variables. Then in the next step, we are extracting the value of first variable by subtracting the value of second variable from the sum and storing it in the second variable.
At last we extract the original value of second variable and store it in first variable.
i.e var1=var1+var2; var2=var1-var2; and var1=var1-var2;
3. Swapping of two numbers using a function
In this program, we will use user-defined function Swap() to swap two numbers. The compiler asks the user to enter two numbers that user wants to swap.
When the compiler visit the line Swap(A, B) then compiler directly jumps on the function Swap(int A, int B)
Output:

4. Swapping of two numbers using pointer
In this program, we will pass the address of variables to two different variables.
Output:

we have assigned the address of variables a and b to the i and j.
5. Swapping Using Call by Reference
Output:

6. Swapping of two numbers Using Bitwise X-OR operator
In this program, we will use bitwise X-OR Operator for swapping of two numbers.
Output:

Explanation:
Let us consider the user enters the value of x and y as 8 and 4.The Binary values of 8 and 4 are 1000 and 0100.
The code is x=x^y i.e x=1000^0100, therefore, the value of x becomes 0011.
After y=x^y i.e y=0011^0100, therefore, the value of y becomes 1000.
Now x=x^y i.e x=0011^1000,therefore, the value of x becomes 0100.Hence both numbers are swapped.1000=8 and 0100=4.
Post a Comment