
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to swap two numbers without using a temp variable in C#
To swap two numbers, use the third variable and perform arithmetical operator without using a temp variable.
Set two variables for swapping −
val1 = 5; val2 = 10;
Now perform the following operation for swap −
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(); } } }
- Related Articles
- Swap two Strings without using temp variable in C#
- Write a Golang program to swap two numbers without using a third variable
- How to swap two numbers without using the third or a temporary variable using C Programming?
- Swap Numbers without using temporary variable in Swift Program?
- How to swap two arrays without using temporary variable in C language?
- How can I swap two strings without using a third variable in Java?
- How to swap two String variables without third variable.
- Swap two Strings without using third user defined variable in Java
- How to Swap Two Numbers in Golang?
- How to Swap Two Numbers in Swift Program?
- Java program to swap two numbers using XOR operator
- Swapping two variable value without using third variable in C/C++
- Swap two numbers in C#
- C++ Program to Swap Two Numbers
- Java Program to Swap Two Numbers.

Advertisements