The Program in C++ to Swap two numbers is given below:
#include <iostream>
using namespace std;
int main() {
int num1, num2, temp;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
//swapping using temporary variable
temp = num1;
num1 = num2;
num2 = temp;
cout << "The first number after swapping: " << num1 << endl;
cout << "The second number after swapping: " << num2 << endl;
return 0;
}
Output:
Enter the first number: 56
Enter the second number: 23
The first number after swapping: 23
The second number after swapping: 56
Pro-Tips💡
This C++ program is used to swap the values of two numbers.
The program starts by including the input/output stream library and using the standard namespace.
Then, it declares two integer variables ‘num1
‘ and ‘num2'
and a temporary variable ‘temp'
.
The program then prompts the user to enter two numbers, which are stored in the variables ‘num1'
and ‘num2'
.
Next, the program uses the temporary variable ‘temp'
to swap the values of ‘num1'
and ‘num2'
. It does this by first storing the value of ‘num1'
in ‘temp'
, then assigning the value of ‘num2
‘ to ‘num1
‘, and finally, assigning the value stored in ‘temp'
to ‘num2'
.
Finally, the program prints the values of 'num1'
and ‘num2'
after swapping, and the program ends.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.