C Sharp swap Number

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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. using System;  
  2.   public class SwapExample  
  3.    {  
  4.      public static void Main(string[] args)  
  5.       {  
  6.        int  a=5, b=10;            
  7.        Console.WriteLine("Before swap a= "+a+" b= "+b);    
  8.        a=a*b; //a=50 (5*10)      
  9.        b=a/b; //b=5 (50/10)      
  10.        a=a/b; //a=10 (50/5)    
  11.        Console.Write("After swap a= "+a+" b= "+b);       
  12.      }  
  13.   }   

Output:

Before swap a= 5 b= 10     
After swap a= 10 b= 5

Program 2: Using + and -

Let's see another example to swap two numbers using + and -.

 
  1. using System;  
  2.   public class SwapExample  
  3.    {  
  4.      public static void Main(string[] args)  
  5.       {  
  6.        int  a=5, b=10;            
  7.        Console.WriteLine("Before swap a= "+a+" b= "+b);    
  8.        a=a+b; //a=15 (5+10)      
  9.        b=a-b; //b=5 (15-10)      
  10.        a=a-b; //a=10 (15-5)   
  11.        Console.Write("After swap a= "+a+" b= "+b);       
  12.       }  
  13.   }  

Output:

Before swap a= 5 b= 10     
After swap a= 10 b= 5