Swap 2 Numbers Using Macros: C Program

Today lets learn how to swap two integer numbers(using a temporary variable) using Macros in C.

Video Tutorial: Swap 2 Numbers Using Macros: C Program



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

Source Code: Swap 2 Numbers Using Macros: C Program

  1. #include<stdio.h>  
  2.   
  3. #define SWAP(x, y, temp) temp = x; x = y; y = temp;  
  4.   
  5. int main()  
  6. {  
  7.     int a, b, temp;  
  8.   
  9.     printf("Enter 2 integer numbers\n");  
  10.     scanf("%d%d", &a, &b);  
  11.   
  12.     printf("Before swapping: a = %d and b = %d\n", a, b);  
  13.   
  14.     SWAP(a, b, temp);  
  15.   
  16.     printf("After swapping: a = %d and b = %d\n", a, b);  
  17.   
  18.     return 0;  
  19. }  

Output:
Enter 2 integer numbers
20
50
Before swapping: a = 20 and b = 50
After swapping: a = 50 and b = 20

Logic To Swap Two Numbers

First value of a is transferred to temp;
Next value of b is transferred to a.
Next value of temp is transferred to b.



That’s how value of a and b are swapped using a temporary variable.

Note: Preprocessor replaces the macro template(SWAP(a, b, temp)) with its corresponding macro expansion(temp = x; x = y; y = temp;) before passing the source code to the compiler.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

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.