Swapping of two number without using 3rd variable in c#


If I have two values assigned to two seperate variables and I want to exchange or swap the values one another without using the third variable. We can do above task easily with a use of 3rd variable, but without using is tedious task. How to swap two number without using 3rd variable in c#

Learn Swapping of two number without using 3rd variable in c#


Let us do a small console application for this task.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{

int first = 12, second = 20;
Console.WriteLine("first value::::" + first);
Console.WriteLine("second value::::" + second + "\n\n");
first = first + second;
second = first - second;
first = first - second;
Console.WriteLine("first value::::" + first);
Console.WriteLine("second value::::" + second);
Console.Read();

}
}
}



From the above code what I am doing is getting the First and Second string from user Input. In the first step I assigned the sum of first and second variable values to First variable. Next subtract first variable and second variable and assigned to Second variable. Third step is subtract first variable and second variable and assigned to first variable.


Comments

Author: Brainstorming Guy08 Feb 2012 Member Level: Gold   Points : 2

Good one. Thanks for sharing it.
The below code will work as well and it's a one line code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int firstNumber = 300;
int secondNumber = 400;
secondNumber = (firstNumber + secondNumber) - (firstNumber = secondNumber);
Console.WriteLine("First Number : {0}", firstNumber);
Console.WriteLine("Second Number : {0}", secondNumber);
}
}
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: