Home > DeveloperSection > Interviews > How to Swap of two number without using 3rd or temp variable?

Posted on    September-14-2016 1:17 AM

 C# C# 
Ratings:
 2 Answer(s)
  684  View(s)
Rate this:

Ailsa Singh
Ailsa Singh

Total Post:7

Points:35
Posted on    September-14-2016 1:17 AM

It is a program to swap two number without using 3rd variable.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplication4

{

    class Program

    {

        static void Main(string[] args)

            int num1, num2;

            string y;

            do

            {

               Console.Write("Enter the First Number : ");

                num1 = Convert.ToInt32(Console.ReadLine());

                Console.Write("Enter the Second Number : ");

                num2 = Convert.ToInt32(Console.ReadLine());

                num1 = num1 + num2;

                num2 = num1 - num2;

                num1 = num1 - num2;

                Console.WriteLine("Swapping is completed \n 1st number is {0} \n 2nd number is {1}", num1, num2);

                Console.WriteLine("Do you want to Repeat Y/N \n");

                y = Console.ReadLine();

          

              

                Console.ReadLine();

                  } while (y == "y" || y == "Y");

            if (y == "n" || y == "N")

            Console.WriteLine("Exiting the program");

            else

            Console.WriteLine("You have entered wrong entry exiting the program");

            Console.ReadLine();

            }

            }

    }


Modified On Sep-14-2016 01:18:43 AM

Abhishek Srivasatava
Abhishek Srivasatava

Total Post:70

Points:350
Posted on    September-14-2016 3:54 AM

It is very useful program for swapping of two number.

I have also another code for the same 

 Console.Writeline("Enter the First Number : ");
                num1 = Convert.ToInt32(Console.ReadLine());
                Console.Write("Enter the Second Number : ");
                num2 = Convert.ToInt32(Console.ReadLine());
                num2=num1*num2/(num1=num2);
                Console.WriteLine(" number1 : {0} number2 : {1}", num1, num2);\



Don't want to miss updates? Please click the below button!

Follow MindStick