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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Jun 16, 2013, 8:56 AM EDT
Sandeep Singh ShekhawatRank #147 · 15.6K reputationPosted Jun 16, 2013, 8:05 AM EDT
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();
}
}
}
Sandeep Singh ShekhawatRank #147 · 15.6K reputationPosted Jun 16, 2013, 8:09 AM EDT
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();
}
}
}
Riyaz AkhtarRank #2,275 · 619 reputationPosted Jun 16, 2013, 10:22 AM EDT
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:
Jignesh TrivediRank #16 · 50.3K reputationPosted Jun 16, 2013, 7:09 PM EDT
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.
suren v112 reputationPosted Jun 16, 2013, 8:18 PM EDT
Really thanks for yours replies :)
Special thanks Vulpes and Sandeep :)