Swap two numbers without using third variable : Program

How to swap two numbers without using the third variable? If you are attending an interview for one or two year experience, 80% of the time you will face this question.

I remember the days when I gave an interview as fresher. This was among the commonly asked interview question asked in almost all of the interviews. Though it’s a simple question. Still, people get confused when to plus and minus.

Here we go with the snippet of code for Swap two numbers without using the third variable

using System;

namespace Swap
{
    class Program
    {
        private static void Main(string[] args)
        {
            int a = 1000;
            int b = 999;
            Console.WriteLine("Before Swap");
            Console.WriteLine("Value of A :{0} ", a);
            Console.WriteLine("Value of B :{0} ", b);
            a = a + b;
            b = a - b;
            a = a - b;
            Console.WriteLine("After Swap");
            Console.WriteLine("Value of A :{0} ", a);
            Console.WriteLine("Value of B :{0} ", b);
            Console.ReadLine();
        }

    }
}

 

Do you think its useful? Feel free to provide your comment and concerns. If you need any help regarding any kind of interview questions and answers, any tutorial. let us know in the comment section. We will try our best to help you.
Close

About The Author

Deependra Kushwah
Deependra kushwah is a member of the fastest growing bloggers community "betechnical", Author, Youtuber, and hardcore Coder. I love writing code in different languages, I also write blogs on tech tutorials, gadgets review and also post some technical videos on youtube on many topics.

This site uses Akismet to reduce spam. Learn how your comment data is processed.