Swap Two Numbers Using a 3rd Variable

C++C++Beginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp/SyntaxandStyleGroup -.-> cpp/comments("`Comments`") cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") subgraph Lab Skills cpp/comments -.-> lab-96227{{"`Swap Two Numbers Using a 3rd Variable`"}} cpp/variables -.-> lab-96227{{"`Swap Two Numbers Using a 3rd Variable`"}} cpp/data_types -.-> lab-96227{{"`Swap Two Numbers Using a 3rd Variable`"}} cpp/operators -.-> lab-96227{{"`Swap Two Numbers Using a 3rd Variable`"}} end

Creating a New C++ File

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

Writing the Code

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;
}

Compiling and Running the Code

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.

Summary

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.

Other C++ Tutorials you may like