Swap two numbers in C#


To swap two numbers, work with the following logic.

Set two variables for swapping −

val1 = 100;
val2 = 200;

Now perform the following operation for swap −

val1 = val1 + val2;
val2 = val1 - val2;
val1 = val1 - val2;

The following is the code −

Example

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         int val1,val2;
         val1 = 100;
         val2 = 200;

         Console.WriteLine("Values before swap...");
         Console.WriteLine(val1.ToString());
         Console.WriteLine(val2.ToString());

         val1 = val1 + val2;
         val2 = val1 - val2;
         val1 = val1 - val2;
   
         Console.WriteLine("Values after swap...");
         Console.WriteLine(val1.ToString());
         Console.WriteLine(val2.ToString());
         Console.ReadLine();
      }
   }
}

Updated on: 21-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements