Swap Two Numbers in C#

C# program: Learn how to swap two integer numbers in C#, here we are swapping the numbers by using two methods - using third variable and without using third variable. By Ridhima Agarwal Last updated : April 15, 2023

Given two integer numbers and we have to swap them.

We are swapping numbers using two methods:

1) Swapping using third variable

To swap numbers, we use a temporary variable to holds the value, firstly we assign first variable to the temporary variable then assign second variable to the first variablecand finally assigns value which is in temporary variable (which holds first number) to the second variable.

C# program to swap two numbers

using System;

namespace swap {
  class ab {
    static void Main(String[] args) {
      int a = 5, b = 3, temp;

      //swapping
      temp = a;
      a = b;
      b = temp;

      Console.WriteLine("Values after swapping are:");
      Console.WriteLine("a=" + a);
      Console.WriteLine("b=" + b);
    }
  }
}

Output

Values after swapping are:
a=3
b=5

2) Swapping without using third variable

Here, we do not use any extra variable to swap the numbers. There are some set of statements (with mathematical operations which performs on the numbers), which swaps the values of variable which are using in these operations.

Example: If we have to swap the values of variable a and b, then the set of statements to swap them, are:

a=a+b;
b=a-b;
a=a-b;

C# program to swap two numbers without using third variable

using System;

namespace swap {
  class ab {
    static void Main(String[] args) {
      int a = 10, b = 20;

      //swapping
      a = a + b;
      b = a - b;
      a = a - b;

      Console.WriteLine("Values after swapping are:");
      Console.WriteLine("a=" + a);
      Console.WriteLine("b=" + b);
    }
  }
}

Output

Values after swapping are:
a=20
b=10

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.