Home > Backend Development > C++ > 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
Release: 2023-09-23 20:09:09
forward
1056 people have browsed it

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.
Copy after login

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;
}
Copy after login

Output

You will get the following output−

enter x and y values:20 30
After swap x=30 and y=20
Copy after login

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;
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template