Swap Numbers Without Third Variable in C++

Beginner

Introduction

In this lab, you'll learn how to swap two numbers without using a third variable in C++. You'll learn a simple and efficient method that can be implemented in any C++ program.

Open your terminal

First, open up your terminal and navigate to the directory where you want to create your C++ file. You can use the following command to navigate to your desired directory.

cd ~/project

Create a new file named main.cpp using the touch command in your terminal:

touch main.cpp

Implement the code in your C++ file

Now that you have created your file, open it in the text editor of your choice and add the following code:

#include <iostream>

int main()
{
    int a, b;

    // Prompt user to enter values for a and b
    std::cout << "Enter value for a and b: \n";
    std::cin >> a >> b;

    // Display the original values of a and b
    std::cout << "Before swapping: a = " << a << ", b = " << b << std::endl;

    // Swap the values of a and b without using a third variable
    a = a + b;
    b = a - b;
    a = a - b;

    // Display the swapped values of a and b
    std::cout << "After swapping: a = " << a << ", b = " << b << std::endl;

    return 0;
}

Compile and run your code

Compile your code using the g++ command:

g++ main.cpp -o main

Run your code using the following command:

./main

You should get an output like the following, where you can input any value for a and b.

Enter value for a and b:
3 5
Before swapping: a = 3, b = 5
After swapping: a = 5, b = 3

Summary

Congratulations! In this lab, you have learned how to swap two numbers without using a third variable in C++. You have learned a simple and efficient method that can be implemented in any C++ program.

Other Tutorials you may like