C# program to swap two numbers without using a temp variable
Here's a C# program that swaps the values of two numbers without using a temporary variable:
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"Before swapping: num1 = {num1}, num2 = {num2}");
SwapNumbers(ref num1, ref num2);
Console.WriteLine($"After swapping: num1 = {num1}, num2 = {num2}");
}
static void SwapNumbers(ref int num1, ref int num2)
{
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
}
}
In this program, the SwapNumbers method takes two integer variables num1 and num2 as input and swaps their values without using a temporary variable. It performs the swap using arithmetic operations.
The Main method prompts the user to enter two numbers, calls the SwapNumbers method with the variables by reference, and displays the values before and after swapping.
Note that the program assumes the user will input valid integers. It doesn't handle exceptions if the input is not a valid integer.