Programming

C++ Program to Swap Two Numbers Without Using Temporary Variable

Write a Program to Swap Two Numbers without Using Temporary Variable.

Algorithm

  • Start the program
  • Input a, b
  • s=a+b, a=s-a, b=s-b
  • Display a, b
  • End the program

Source Code

#include<iostream>

using namespace std;

int main() {
    int a,b,s;
    cout<<"Enter two integer numbers:";
    cin>>a>>b;
    cout<<"\nThe entered numbers are: "<<"a = "<<a<<" b = "<<b;
    s=a+b;
    a=s-a;
    b=s-b;
    cout<<"After swapping, the numbers are: "<<"a = "<<a<<" b = "<<b;
}

Output

Swap Two Numbers

Tuts

About Author

Tutsmaster.org provides tutorials related to tech and programmings. We are also setting up a community for the users and students.