Online Snippets Library

Swapping values of two variables without using third variable in C

Some times developer need to swap variable without using thrid variable.We need to use following steps to swap two variable without using third variable.

  • Add variable1, variable2 and store values in variable1.
  • Subtract variable2 from variable1 and store to variable2.Now variable2 has value of variable1.
  • Subtract variable2 from variable1 and store to variable1.Now variable1 has value of variable2.
C Program
#include <stdio.h>
int main() {
   int num1, num2;

   num1 = 10;
   num2 = 90;

   printf("Values before swapping - \n a = %d, b = %d \n\n", num1, num2);

   num1 = num1 + num2;  // ( 10 + 90 = 100)
   num2 = num1 - num2;  // ( 100 - 90 = 10)
   num1 = num1 - num2;  // ( 100 - 10 = 90)

   printf("Values after swapping - \n a = %d, b = %d \n", num1, num2);
}

Output

Values before swapping - a = 10, b = 90 Values after swapping - a = 90, b = 10