Swap Two Number Program in C#

Google 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

Google Advertisements

Buy This Ad Space @$50 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

Cloud computing is the on demand availability of computer system resources, especially data storage and computing power, without direct active management by the user. Cloud Computing Tutorial

College Projects Related to Java, AWT, C Projects for College, C++ Projects for College, Android Projects. Download Java C C++ Projects

Download Projects

Adsense Advertisements


Buy This ads Space 8076671483

Buy This Ad Space @$120 per Month, Ad Size 300X600 Contact on: hitesh.xc@gmail.com or 8076671483 Try this Keyword C++ Programs