Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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();
}
}
}Advertisements