C++ program to swap two numbers

In this example, you will learn a c++ program to swap two numbers. This program takes two numbers from the user like 2 and 5 and swaps them.  The first number 2 becomes 5 and the second number 5 becomes 2.

Prerequisite

To understand this example perfectly you should have the following C++ programming knowledge.

  • C++ Variables
  • C++ Assignment Operators

Program: Swap two numbers

//C++ program to swap two numbers
#include<iostream>
using namespace std;

int main()
{
int number1, number2, temp;
cout<<"Enter first number: ";
cin>>number1;
cout<<"Enter second number: ";
cin>>number2;
temp=number1;
number1=number2;
number2=temp;
cout<<"First numbr afer swap: "<<number1<<endl;
cout<<"Second number after swap: "<<number2<<endl;
return 0;
}

Output

Enter first number: 2
Enter second number: 5
First numbr afer swap: 5
Second number after swap: 2

Description and working of this program

  • Take two numbers from the user and named them“number1” and “number2”
  • Initialize a third variable called “temp”
  • Now assign the “number1” value to the “temp” variable
  • Assign the “number2” value to the “number1”
  • And at the end assign the “temp” value to the “number2”
  • Display the result on the screen.