Home >Backend Development >C++ >How to swap two numbers in C programming without using third or temporary variable?
We can swap two numbers from one memory location to another through addition and subtraction operations.
The following is an explanation of the algorithm−
Step 1: Declare 2 variables x and y. Step 2: Read two numbers from keyboard. Step 3: Swap numbers. //Apply addition and subtraction operations to swap the numbers. i. x=x+y ii. y=x-y iii. x=x-y Step 4: Print x and y values.
The following is a C program to explain how Swap two numbers without using a third variable or a temporary variable:
#include<stdio.h> int main(){ int x,y; printf("enter x and y values:"); scanf("%d%d",&x,&y);// lets take x as 20 and y as 30 x=x+y;// x=20+30=50 y=x-y;//y=50-30=20 x=x-y;//x=50-20=30 printf("After swap x=%d and y=%d",x,y); return 0; }
You will get the following output−
enter x and y values:20 30 After swap x=30 and y=20
Note - We can use multiplication, division and bitwise XOR operators to swap two numbers without using a third variable.
Consider another example that explains how to use the multiplication and division operators to swap two numbers.
The following is a C program that demonstrates the corresponding function of exchanging two numbers:
#include<stdio.h> int main(){ int x,y; printf("enter x and y values:"); scanf("%d%d",&x,&y); x=x*y; y=x/y; x=x/y; printf("After swap x=%d and y=%d",x,y); return 0; }
When you execute the above program, you will get the following output −
enter x and y values:120 250 After swap x=250 and y=120
The above is the detailed content of How to swap two numbers in C programming without using third or temporary variable?. For more information, please follow other related articles on the PHP Chinese website!