Menu

Add Topic

programming

waiting answer September 13, 2021

Swapping Of Two Numbers Without Using Third Variable in C Language

Answers
September 13, 2021

There are two ways to swap two numbers without using the third variable in the c language

  1. By using the Arithmetic operators + and -
  2. By using the Arithmetic operators * and /
  3. By using Bitwise operators

By using + and -

    #include  
    int main()    
    {    
        int a=100, b=200;      
        printf("Before swapping a=%d b=%d",a,b);      
        a=a+b;//a=100 (100+200)    
        b=a-b;//b=200 (300-200)    
        a=a-b;//a=200 (300-100)    
        printf("\nAfter swapping a=%d b=%d",a,b);    
        return 0;  
    }  

Instead of above logic, you can also use

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

By using * and /

    #include  
    int main()    
    {    
        int a=100, b=200;      
        printf("Before swap a=%d b=%d",a,b);       
        a=a*b;   
        b=a/b;    
        a=a/b;    
        printf("\nAfter swap a=%d b=%d",a,b);       
        return 0;  
    } 

To implement this logic in a single line, you can use

          a = (a * b) / (b = a);

By using Bitwise operators

    #include  

    int main()    
    {    
        int a, b;
        printf("Enter two numbers: ");
        scanf("%d %d", &a, &b); 
        a = a ^ b; 
        b = a ^ b;
        a = a ^ b;
        printf("Numbers after swaping: %d %d", a, b);    
        return 0;  
    }   

Output

         Enter two numbers: 11 22
         Numbers after swaping: 22 11

0 0

Please Login to Post the answer

Leave an Answer