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 https://www.youtube.com/watch?v=esQ-DmyPYYc]

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

#include<stdio.h>

#define SWAP(x, y, temp) temp = x; x = y; y = temp;

int main()
{
    int a, b, temp;

    printf("Enter 2 integer numbers\n");
    scanf("%d%d", &a, &b);

    printf("Before swapping: a = %d and b = %d\n", a, b);

    SWAP(a, b, temp);

    printf("After swapping: a = %d and b = %d\n", a, b);

    return 0;
}

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.

 
#include < stdio.h >

int main()
{
    int x = 10, y = 20, temp;

    printf("X = %d, Y = %d\n", x, y);
    
    temp = x;
    x    = y;
    y    = temp;

    printf("After swapping X = %d, Y = %d\n", x, y);

    return 0;
}


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

Swap 2 Numbers Using a Temporary Variable: C


[youtube https://www.youtube.com/watch?v=f_JBCYWS2uw]

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.