Swapping two variable value without using third variable in C/C++


The following is an example of swapping two variables.

Example

 Live Demo

#include <stdio.h>
int main() {
   int a,b;
   printf("Enter the value of a : ");
   scanf("%d", &a);
   printf("\nEnter the value of b : ");
   scanf("%d", &b);
   a += b -= a = b - a;
   printf("\nAfter Swapping : %d\t%d", a, b);
   return 0;
}

Output

Enter the value of a : 23
Enter the value of b : 43
After Swapping : 4323

In the above program, two variables a and b are declared and initialized dynamically at run time.

int a,b;
printf("Enter the value of a : ");
scanf("%d", &a);
printf("\nEnter the value of b : ");
scanf("%d", &b);

Numbers are swapped without using any third variable.

a += b -= a = b - a;

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

408 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements