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. After the swap, the first number 2 becomes 5 and the second number 5 becomes 2.

Example: C++ program to 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

cpp program to swap two numbers

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.

Recommended Articles

C++ Variables

C++ Operators