To swap two numbers, you can use a third variable and perform arithmetic operators without using temporary variables.
Set two variables for exchange −
val1 = 5; val2 = 10;
Now perform the following exchange operation -
val1 = val1 + val2; val2 = val1 - val2; val1 = val1 - val2;
using System; namespace Demo { class Program { static void Main(string[] args) { int val1,val2; val1 = 5; val2 = 10; 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(); } } }
The above is the detailed content of How to swap two numbers in C# without using temporary variables. For more information, please follow other related articles on the PHP Chinese website!