Home >Backend Development >C#.Net Tutorial >How to swap two numbers in C# without using temporary variables

How to swap two numbers in C# without using temporary variables

王林
王林forward
2023-09-10 16:37:021110browse

如何在 C# 中不使用临时变量交换两个数字

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;

Example

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete