Swapping two integers in  C - The easy  method

Swapping two integers in C - The easy method

ยท

1 min read

Table of contents

No heading

No headings in the article.

I recently had this task where I had to swap 2 integers, and man, didn't bugs have a field day?

When I was almost giving up, everything clicked into place. I could almost swear a light bulb lit up somewhere in my head. I really believe that it's the easiest method out there.

Now let me explain it using some C code.

#include <stdio.h>

int main(void)
{
    int a, b, temp;  //here I have declared three integers

    a = 20;
    b = 30; //I have initialised 'a' and 'b' and not 'temp'
            //'temp' will be a holding ground for the values 
            //of 'a' and 'b' while we are swapping them 

    temp = a; //here 'temp' assumes the value of 'a'
               //'temp' = 20;
                // 'a' = 'nothing';
    a = b; // 'a' assumes the values of 'b' as the value
            //of 'a' is being temporarily held in 'temp'
            // 'temp' = 20;
               //'a' = 30;
              //'b' = 'nothing';
    b = temp; // you guessed it, 'b' assumes the value of 
                //'temp'.
            // 'temp' = 'nothing';
               //'a' = 30;
              //'b' = '20';    
    printf("a = %d, b = %d\n", a, b);

When we run the above code this is what is printed:

I hope that you learned something.

ย