How to swap two numbers without using the third or a temporary variable using C Programming?


With the help of addition and subtraction operations, we can swap two numbers from one memory location to another memory location.

Algorithm

The algorithm is explained below −

START

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.

Program

Following is the C program which explains swapping of two numbers without using 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;
}

Output

You will get the following output −

enter x and y values:20 30
After swap x=30 and y=20

Note − We can swap two numbers by using multiplication and division and bitwise XOR operators without taking third variable help.

Consider another example which explains how to swap two numbers by using multiplication and division operators.

Program

Following is the C program to demonstrate the respective functioning of swapping 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;
}

Output

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

Updated on: 15-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements