Hai,Good Evening Dudes,
I want to swapping 2 or 3 numbers in C#...Like This
a=5,b=3 how to change this a=3, b=5 ? ? ?
Thanks In Advance Frnds :)
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Jun 16, 2013, 12:56 PM
suren vPosted Jun 17, 2013, 12:18 AM
Really thanks for yours replies :)
Special thanks Vulpes and Sandeep :)
Jignesh TrivediPosted Jun 16, 2013, 11:09 PM
you may use bitwise exclusive or operator to swap two number
example.
int x = 10;
int y = 12;
x ^= y;
y ^= x;
x ^= y;
you may also swap string without use third string
string a = "jignesh";
string b = "Trivedi";
a += b;
b = a.Substring(0, a.Length - b.Length);
a = a.Substring(b.Length);
hope this will help you.
Riyaz AkhtarPosted Jun 16, 2013, 2:22 PM
But when i saw your question, i remembered my college day's question : swapping two number without any 3rd variable
if you are looking for the same then here is the answer:
Method 1:
Method 2:
Sandeep Singh ShekhawatPosted Jun 16, 2013, 12:09 PM
using System;
namespace SwapNumber
{
class Program
{
static void Main(string[] args)
{
int a = 5, b = 3;
int c = 0;
c = a;
a = b;
b = c;
Console.WriteLine("a={0} and b={1}", a, b);
Console.ReadKey();
}
}
}
Sandeep Singh ShekhawatPosted Jun 16, 2013, 12:05 PM
namespace SwapNumber
{
class Program
{
static void Main(string[] args)
{
int firtsNumber = 10, secondNumber = 20;
Console.WriteLine("First Number = {0} and Second Number = {1}", firtsNumber, secondNumber);
firtsNumber += secondNumber;
secondNumber = firtsNumber - secondNumber;
firtsNumber = firtsNumber - secondNumber;
Console.WriteLine("First Number = {0} and Second Number = {1}", firtsNumber, secondNumber);
Console.ReadLine();
}
}
}