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 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.