Swap Two Number Program in C#


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

Google Advertisements
Download Projects

Google Adsense Advertisements

Buy 3 Year Old Domain, Tutorialday.com, SeosmoTools.com @$200

Buy This Ad Space @$50 per Month, Ad Size 300X250 Contact on: hitesh.xc@gmail.com WhatsApp no. 8882538826

Yahoo Advertisements