Swap 2 Numbers Without Using a Temporary Variable: C

Today lets learn how to swap 2 integer numbers without using a temporary variable in C. We’re using arithmetic operation in our logic. We’re using addition and subtraction in this c program to swap the 2 numbers.

  1.    
  2. #include < stdio.h >  
  3.   
  4. int main()  
  5. {  
  6.     int x = 10, y = 5;  
  7.   
  8.     printf("Before swapping x = %d and y = %d\n", x, y);  
  9.   
  10.     x = x + y - ( y = x );  
  11.   
  12.     printf("After swapping x = %d and y = %d\n", x, y);  
  13.   
  14.     return 0;  
  15. }  

Output:
Before swapping x = 10 and y = 5
After swapping x = 5 and y = 10

Swap 2 Numbers Without Using a Temporary Variable: C



YouTube Link: https://www.youtube.com/watch?v=tTzdGK5t-X4 [Watch the Video In Full Screen.]


Swapping 2 Numbers In C using addition, subtraction and assignment operators: Logic

Here we take 2 variables, x and y; We store 10 in x and 5 in y.

We add the values of x(10) and y(5) and then subtract the value returned when we assign x value to y.

Note: When we assign a value to a variable, the same value is returned.
Ex: temp = (a = 10);
In this statement, when we assign 10 to a, the whole expression returns 10 and we can store it in variable temp, for our reference.