C Program to swap two numbers without third variable


We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable:

  1. By + and -
  2. By * and /

Program 1: Using + and -

Let's see a simple c example to swap two numbers without using third variable.

  1. #include<stdio.h>  
  2.  int main()    
  3. {    
  4. int a=10, b=20;      
  5. printf("Before swap a=%d b=%d",a,b);      
  6. a=a+b;//a=30 (10+20)    
  7. b=a-b;//b=10 (30-20)    
  8. a=a-b;//a=20 (30-10)    
  9. printf("\nAfter swap a=%d b=%d",a,b);    
  10. return 0;  
  11. }   

Output:

Before swap a=10 b=20
After swap a=20 b=10

Program 2: Using * and /

Let's see another example to swap two numbers using * and /.

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3.  int main()    
  4. {    
  5. int a=10, b=20;      
  6. printf("Before swap a=%d b=%d",a,b);       
  7. a=a*b;//a=200 (10*20)    
  8. b=a/b;//b=10 (200/20)    
  9. a=a/b;//a=20 (200/10)    
  10.  system("cls");  
  11. printf("\nAfter swap a=%d b=%d",a,b);       
  12. return 0;  
  13. }   

Output:

Before swap a=10 b=20
After swap a=20 b=10
Previous Post Next Post