In this C++ program, we need to swap the values in two variables.
Swapping means exchanging, In our case, swapping is exchanging some variable's value. For example, If you have a=1 and b=2, the values of the variables a and b are mutually exchanged. After swapping the result are a=2 and b=1. This operation can be made either by using an extra variable or can be done without the help of an additional variable. The simplest method to swap two variables is to use a third variable.
The program always starts with the main() function. Within the main() function's body, declare 3 integer type variables to store the two numbers and one is a temporary variable used to help to swap operation.
Ask the user to enter two numbers using the object cout
and read the entered values to two variables a and b using the object cin.
Display the current value of the variables a and on the screen using cout.
Access the next line with the help of the command endl
. endl
is a command or a manipulator used to insert a new line character.
The content of the first variable is copied into the temp variable. Then the content of the second variable is copied to the first variable. Now the content of the temporary variable is copied to the second variable. And now the swapping process is completed. Display the result after swapping on the screen using cout.
For example
Step 1: Call the header file iostream.
Step 2: Use the namespace std.
Step 3: Open the main function as an integer type; int main().
Step 4: Declare integer type variables; a, b, temp.
Step 5: Print a message on the screen to “Enter two numbers:” using cout.
Step 6: Read the first number to variable a and the second number to variable b using cin.
Step 7: Display the values of variables before swapping on the screen using cout.
Step8 : Perform swapping.
Step 9: Display the values of variable a and after swapping on the screen.
Step 10: Exit.
#include <iostream>
using namespace std;
int main() {
int a, b, temp;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Enter two numbers: 10 20 Before swapping. a = 10, b = 20 After swapping. a = 20, b = 10