Thursday 2 August 2012

How to swap numbers without a temporary variable in C++


How to swap numbers without a temporary variable in C++
Program to read two numbers from the user and swap them without using third variable.




#include<iostream>

#include<conio.h>

using namespace std;

int main()
{
       int first_number = 0, second_number = 0;

       cout << "\n\t__ Program to swap two numbers without using a Temporary Variable ___";

       cout << "\n\n\n  Enter the First Number  - ";

       cin >> first_number;

       cout << "\n\n  Enter the Second Number - ";

       cin >>  second_number;

       first_number = first_number +  second_number;

       second_number = first_number - second_number;

       first_number = first_number - second_number;

       cout << "\n\n  Result - ";

       cout << "\n\n\t\t____  First Number  - " << first_number;

       cout << "\t  Second Number - " << second_number << "  ____";

       getch();

       return 0;

}


To swap two numbers without using a temporary variable, first scan the two numbers, add those numbers and store the result in the first number. Then subtract second number from first number and store the result in the second number in this way the value of the original first number is assigned to second number. Similarly, subtract the second number from first number and store it in the first number.

No comments:

Post a Comment