Swap Two Number Program in C#

Advertisements

Prev Tutorial Next Tutorial

Swap Two Numbers Program in C#

There are two method to swap any two numbers, using third variable and without using third variable. here we write this code using third variable and without using third variable.

Swap Two Numbers Using third variable Program in C#

using System;  
  public class Swap_Demo  
   {  
     public static void Main(string[] args)  
      {  
       int  a=10, b=20, temp;            
       Console.WriteLine("Before swap a= "+a+" b= "+b);    
       temp=a;  //temp=10      
       a=b;  //a=20      
       b=temp;  //b=10   
       Console.Write("After swap a= "+a+" b= "+b);       
      }  
  }

Output

Before Swap a= 10 b=20
After Swap a= 20 b=10

Swap Two Numbers without using third variable Program in C#

using System;  

  public class Swap_Demo  
  {  
  public static void Main(string[] args)  
  {  
   int  a=10, b=20;            
   Console.WriteLine("Before swap a= "+a+" b= "+b);    
   a=a+b; //a=30 (10+20)      
   b=a-b; //b=10 (30-20)      
   a=a-b; //a=20 (30-10)   
   Console.Write("After swap a= "+a+" b= "+b);       
  }  
  }

Output

Before Swap a= 10 b=20
After Swap a= 20 b=10

Swap Two Numbers without using third variable Program in C#

using System;  
 public class Swap_Demo  
 {  
 public static void Main(string[] args)  
 {  
 int a, b;          
 Console.Write("\nInput the First Number: ");
 a = int.Parse(Console.ReadLine());
 Console.Write("\nInput the Second Number: ");
 b = int.Parse(Console.ReadLine());      
 Console.WriteLine("Before swap a= "+a+" b= "+b);    
 a=a+b; //a=30 (10+20)      
 b=a-b; //b=10 (30-20)      
 a=a-b; //a=20 (30-10)   
 Console.Write("After swap a= "+a+" b= "+b);       
 }  
}

Output

Input the First Number: 10
Input the Second Number: 20
Before Swap a= 10 b=20
After Swap a= 20 b=10

Prev Tutorial Next Tutorial

Advertisements

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 8076671483

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

Download Projects

Advertisements


Buy Websites 9999595223

Buy Fresh and Payment Receive Media.net Account with Website. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs