Swap Numbers in C Sharp

Swap Numbers

In C#, we can swap two numbers without using a third variable, using either of the two ways:

  1. By using the + and – operators
  2. By using the * and / operators

Example 1: Using ∗ and / operators.

using System;  
  public class Example  
   {  
     public static void Main(string[] args)  
      {  
       int  x=20, y=30;            
       Console.WriteLine("Before swap:"); 
       Console.WriteLine("x = " + x + " and y = " + y); 
       x = x*y;       
       y = x/y; 
       x = x/y; 
       Console.WriteLine("After swap:"); 
       Console.WriteLine("x = " + x + " and y = " + y); 
     }  
  }

Output:

Explanation:

In the above example, we are swapping two numbers without using a third variable and by using * and / operators.

Example 2: Using + and – operators.

using System;  
  public class Example  
   {  
     public static void Main(string[] args)  
      {  
       int  x=20, y=30;            
       Console.WriteLine("Before swap:"); 
       Console.WriteLine("x = " + x + " and y = " + y); 
       x = x+y;       
       y = x-y; 
       x = x-y; 
       Console.WriteLine("After swap:"); 
       Console.WriteLine("x = " + x + " and y = " + y); 
     }  
  }

Output:

Explanation:

In the above example, we are swapping two numbers without using a third variable and by using + and – operators.

Please Share