Thursday, April 25, 2024
HomeC ProgrammingSwapping Variables – Answer | C For Dummies Weblog

Swapping Variables – Answer | C For Dummies Weblog


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

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

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 unique a is subtracted, what’s left over is b, which is assigned to a: a = b - a

Lastly, the brand new worth of a (unique 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 good or such an answer isn’t attainable. Regardless, right here is the complete answer:

2023_06-Train.c


#embody <stdio.h>

int essential()
{
    int a,b;

    printf("Enter worth A: ");
    scanf("%d",&a);
    printf("Enter worth B: ");
    scanf("%d",&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);

    return(0);
}

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments