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.

 
#include < stdio.h >

int main()
{
    int x = 10, y = 5;

    printf("Before swapping x = %d and y = %d\n", x, y);

    x = x + y - ( y = x );

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

    return 0;
}


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

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.

Leave a Reply

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