In this article, you will learn a C++ program to interchange two numbers. We can interchange two numbers by using the same technique as swapping.
For this program, we will use a “temp” as a supporting variable to temporary hold the value. If we have two numbers 4 and 7, After interchange 7 becomes 4, and 4 becomes 7.
Let’s look at the program.
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
Description: Interchange two numbers
- Take two numbers from the user and store them into variables “number1” and “number2”
- Initialize the third variable named “temp” to temporary hold the value
- Assign “number1” value to “temp” variable
- Now assign the “number2” value to “number1”
- In the end, assign the “temp” value to “number2”
- Display the interchanged value on the console screen.