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

王林
Release: 2023-09-10 16:37:02
forward
1071 people have browsed it

如何在 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;
Copy after login

Now perform the following exchange operation -

val1 = val1 + val2;
val2 = val1 - val2;
val1 = val1 - val2;
Copy after login

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();
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template