Swapping Variables

swapping variables


This month’s Train challenges you to swapping variables values with out utilizing a 3rd variable. It’s an answer broadly obtainable on the Web, however your job is to determine the approach with out wanting elsewhere.

I confess that I noticed this answer months in the past and marveled at it. However I forgot the specifics. Somewhat than look it up once more, I got down to devise it alone, utilizing solely my imprecise reminiscence of the mathematical operations used on the 2 variables to swap values. Listed here are the three statements I exploit:

Swapping Variables Values

b = b + a;
a = b - a;
b = b - a;

Sure, it took me some time to hone this end result, which works for each signed and unsigned values. Determine 1 helps illustrate how the operation works.

Determine 1. Swapping two variables’ values by utilizing solely two variables.

Successfully, variable b turns into what would in any other case be swapping variable c. First it holds the sum of a and b: b = b + a

When authentic a is subtracted, what’s left over is b, which is assigned to a: a = b - a

Lastly, the brand new worth of a (authentic b) is subtracted from new b, which yields the unique worth of a, assigned to b: b = b - a

It took my mind a couple of minutes to just accept this answer. I even tried to condense it to solely two statements, however both I’m not that sensible or such an answer isn’t doable. Regardless, right here is the total answer:


#embody <stdio.h>

int principal()
    int a,b;

    printf("Enter worth A: ");
    printf("Enter worth B: ");

    printf("Earlier than: A=%d, B=%dn",a,b);

    b = b + a;
    a = b - a;
    b = b - a;

    printf("After: A=%d, B=%dn",a,b);


After scripting this code, I checked the interwebs to see what I discovered earlier, the inspiration for this Train. Yep, I bought it proper. I hope you probably did as nicely.

You can also Read : Enforced Bounds Checking for Frozen Perform Interfaces


Leave a Reply

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