Home  >  Article  >  Backend Development  >  How to swap two numbers in C programming without using third or temporary variable?

How to swap two numbers in C programming without using third or temporary variable?

WBOY
WBOYforward
2023-09-23 20:09:091016browse

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.

Algorithm

The following is an explanation of the algorithm−

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

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;
}

Output

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.

Program

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;
}

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete