C++ program to interchange two numbers

In this program, you will learn a C++ program to interchange two numbers. We can interchange two numbers same as swapping. Let’s look at the program.

Prerequisite

For a better understanding of this program, you should have the following C++ programming knowledge.

Example 1: C++ program to interchange two numbers

//C++ program to interchange 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 interchange: "<<number1<<endl;
cout<<"Second number after interchange: "<<number2<<endl;
return 0;
}

Output

Enter first number: 4
Enter second number: 7
First numbr afer interchange: 7
Second number after interchange: 4

 Description: Interchange two numbers

  • Take three numbers from the user and store them into variables named “number1”, “number2”, and “Temp”
  • Take two numbers from the user to store into “number1” and “number2”
  • Assign “number1” value to “temp” variable
  • Now assign the “number2” value to “number1”
  • At the end assign the “temp” value to “number2”
  • Display the interchanged value on the screen.