Search This Blog

Four Different Methods or Tricks to Swap Two Numbers Without Using a Third Variable

In this post, we will see four different methods in c to swap two variables without using a third variable. This type of questions are often asked in technical interviews. Here we will see four different C programs to swap two numbers without a third temporary variable. Using a third variable is not an overhead. But still this kinda questions are asked in technical interviews for programming jobs to test your knowledge in the language.

Trick 1

In the first c program to swap two numbers without a third variable, we swap the values of the two variables in 3 steps which are simple addition and subtractions.

#include<stdio.h>
void main(){
    int a=5,b=10;
    a=b+a; //now a =15
    b=a-b; //now b= 5
    a=a-b; // now a=10 (done)
    printf("a= %d\nb=  %d",a,b);
}


Trick 2

In the second c program to swap two numbers without a third variable, we swap them in a single statement. The statement contains an assignment, addition and subtraction.

#include<stdio.h>
void main(){
    int a=10,b=30;
    a=a+b-(b=a);
    //10+30-(10)  a becomes 30
    // b is assigned with 10 in the same line of code
    printf("a= %d\nb=  %d",a,b);
}

Trick 3

In the third c code, we swap the numbers using bitwise XOR operation. The bitwise operator ^ 
is used in the program. The binary representation of the numbers, the bitwise xor operation on them and the result are shown in the c program as comments. The program is as follows:

#include<stdio.h>
void main(){
    int a=8,b=12;

   /* a: 8 : 01000
       b:12 : 01100
    */
   
    a=a^b; 

    /*      01000 ^
            01100
       a=   00100 (4)
    */


    b=a^b;

    /*      00100 ^
            01100
       b=   01000 (8)
    */

a=b^a;

    /*      01000 ^
            00100
       a=   01100 (12)
    */



    printf("a= %d\nb=  %d",a,b);
}

Trick 4

In the fourth method to swap two numbers without a temporary variable, we swap the numbers using a combination of addition, subtraction and bitwise NOT (inversion) operation. The bitwise operator 
is used in the program. The binary representation of the numbers, the bitwise NOT operation on them and the result are shown in the c program as comments. The program is as follows:

#include<stdio.h>
void main(){

    int a=14,b=4;
    
   /* a: 14 : 1110
      b:  4 : 0100
     ~a:   :  0001  
     ~b:   :  1011  
   */
   a=b-~a-1;
    /* b:   0100 -
      ~a:   0001
            0011 -
       1:   0001
            0010
     now a= 0010 
    */
    b=a+~b+1;
    /* a:   0010 +
      ~b:   1011
       1:   0001
    now b:  1110  (14)
       ~b:  0001
    */
    a=a+~b+1;
   /*  a:   0010 +
      ~b:   0001
       1:   0001
    now a:  0100 (4)
   */

    printf("a= %d\nb=  %d",a,b);
}

No comments: