Swap two variables

How to swap two variables without using third variable?

A variable is a named location in memory that is used to store data which can be modified in a program. Let us learn how to swap two variables without using third variable. This can be done in number of ways

  • By using arithmetic operators
  • By using Bitwise operators
  • By using Pointers Concept and so on

One of the method is by using arithmetic operators. Consider 2 variables say x=50 and y=70. To swap the value of two variables that is make x=70 and y=50 without using third variable can be done by using following arithmetic operations

x = x + y;
y = x – y;
x = x – y;

which gives

x = x + y gives x= 70 + 50 an so x is equal to 120
y = x – y gives y = 120 – 70 which makes the value of y as 50
x = x – y gives x= 120 – 50 and thus value of x becomes 70

Thus value of x and y gets swapped without using third variable and the whole program is given below:

main()
{
    int x = 50, y = 70;
    x = x + y;
    y = x – y;
    x = x – y;
    printf(“x=%d y=%d”, x,y);
}

This program gives output as

        x=70 y=50

Editorial Team at Geekinterview is a team of HR and Career Advice members led by Chandra Vennapoosa.

Editorial Team – who has written posts on Online Learning.


Pin It