Introduction
In this lab, we will learn how to swap two numbers using a third variable in the C++ programming language. Swapping two numbers is a common programming problem and there are different ways to achieve this task.
In this lab, we will learn how to swap two numbers using a third variable in the C++ programming language. Swapping two numbers is a common programming problem and there are different ways to achieve this task.
First, let's create a new C++ file named main.cpp
in the ~/project
directory using the following command in the terminal:
touch ~/project/main.cpp
Next, let's write the code to swap two numbers using a third variable. Copy and paste the following code into the main.cpp
file:
#include <iostream>
using namespace std;
int main()
{
// Declare variables
int a, b, temp;
// Input two numbers
cout << "Enter first number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
// Print the original values of the two numbers
cout << "\nValues before swapping: "<<endl;
cout << "First number: " << a << endl;
cout << "Second number: " << b << endl;
// Swap the two numbers using a third variable
temp = a;
a = b;
b = temp;
// Print the swapped values of the two numbers
cout << "\nValues after swapping: " << endl;
cout << "First number: " << a << endl;
cout << "Second number: " << b << endl;
return 0;
}
Now let's compile and run the code to see the output. In the terminal, navigate to the ~/project
directory and use the following command to compile the code:
g++ main.cpp -o main
This command will create an executable file named main
in the same directory.
Next, run the executable file using the following command:
./main
This will run the C++ program, which will ask you to input two numbers. After you enter the numbers, the program will swap them using a third variable and output the original and swapped values of the two numbers.
In this lab, we learned how to swap two numbers using a third variable in the C++ programming language. Swapping two numbers can be useful when we want to exchange the values of two variables. By using a third variable, we can easily swap two numbers without losing any values.