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

CC++Server Side Programming

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;
raja
Published on 08-Nov-2018 05:55:14
Advertisements