Swap 2 Numbers Using a Temporary Variable: C


Today lets learn how to swap 2 integer numbers using a temporary variable in C.

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

Output:
X = 10, Y = 20
After swapping X = 20, Y = 10

Swap 2 Numbers Using a Temporary Variable: C



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


Swapping 2 Numbers In C: Logic

Here we take 3 variables, x, y and temp; We store 10 in x and 20 in y.
1. First we copy the value present in x to temp. So now, both x and temp variables have value 10.
2. Next we copy value of y to x. So now, both x and y have value 20.
3. Next, copy the value of temp to y. So now both y and temp have value 10.

Finally after executing above 3 step logic, x has value 20 and y has a value of 10 in it.

Leave a Reply

Your email address will not be published. Required fields are marked *