In this code snippet, we will see how to Swap 2 Numbers in C#. This C# program provides an easy way to sway 2 numbers using temp variable.
using System;
namespace SampleProgram
{
class SwapNumbers
{
static void Main(string[] args)
{
// Declaration
int number1;
int number2;
int temp;
// Capture input
Console.Write("\nEnter the First Number : ");
number1 = int.Parse(Console.ReadLine());
Console.Write("\nEnter the Second Number : ");
number2 = int.Parse(Console.ReadLine());
// Print numbers before swaping
Console.Write("\nBefore Swapping : ");
Console.Write("\nFirst Number : " + number1);
Console.Write("\nSecond Number : " + number2);
Console.Write("\n\n");
// Swap numbers using temp variable
temp = number1;
number1 = number2;
number2 = temp;
// Print numbers after swaping
Console.Write("\nAfter Swapping : ");
Console.Write("\nFirst Number : " + number1);
Console.Write("\nSecond Number : " + number2);
Console.ReadKey();
}
}
}
Output:
Enter the First Number : 25
Enter the Second Number : 60
Before Swapping :
First Number : 25
Second Number : 60
After Swapping :
First Number : 60
Second Number : 25
Comments (0)