csharp

Swap two numbers without using third variable in c#.

In this article, we will learn how to Swap two numbers without using third variable in c#.
This C# Program Swaps 2 Numbers. It obtains two numbers from the user and swaps the numbers without using third variable.

We will see multiple ways to Swap two numbers without using third variable in c#.

First Way:
[php]
/*
* C# Program to Swap two Numbers without third variable
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SwapProgram
{
class Program
{
static void Main(string[] args)
{

int firstNumber, secondNumber;
Console.WriteLine("Enter first number :");
firstNumber = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Secondnumber number :");
secondNumber = int.Parse(Console.ReadLine());
Console.WriteLine("Before Swapping :");
Console.WriteLine("First Number :" + firstNumber);
Console.WriteLine("Second Number :" + secondNumber);
//Swapping
firstNumber = firstNumber * secondNumber;
secondNumber = firstNumber / secondNumber;
firstNumber = firstNumber / secondNumber;
Console.WriteLine("After swapping :");
Console.WriteLine("First Number :" + firstNumber);
Console.WriteLine("Second Number :" + secondNumber);
Console.ReadKey();
}
}
}

[/php]

Second Way:
[php]
/*
* C# Program to Swap two Numbers without third variable
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SwapProgram
{
class Program
{
static void Main(string[] args)
{

int firstNumber, secondNumber;
Console.WriteLine("Enter first number :");
firstNumber = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Secondnumber number :");
secondNumber = int.Parse(Console.ReadLine());
Console.WriteLine("Before Swapping :");
Console.WriteLine("First Number :" + firstNumber);
Console.WriteLine("Second Number :" + secondNumber);
//Swapping
firstNumber = firstNumber + secondNumber;
secondNumber = firstNumber – secondNumber;
firstNumber = firstNumber – secondNumber;
Console.WriteLine("After swapping :");
Console.WriteLine("First Number :" + firstNumber);
Console.WriteLine("Second Number :" + secondNumber);
Console.ReadKey();
}
}
}

[/php]
Output