Invert the value of two variables in C++


  • 03. Make a program that asks for two integers and store in two variables. Then swap the value of the variables and display on screen
Exercise of the conditional statement tutorial.

How to swap the value of two numbers in C++

Let's ask the user two numbers and store in variables num1 and num2.

Now let's change, invert these values.
The first variable receives the value of the second:
  • num1 = num2;

Now the second gets the value of the first:
  • num2 = num1;

Simple and easy, no?
No. It's wrong!

The first operation is ok, now the value of num1 is num2.

However, when we make the second variable take the value of the first, that value of the first has changed, it is no longer the original, it is lost, now what has in the first variable is the value of the second.

What we have to do is store the initial value of this first variable.
Let's store in an auxiliary variable, aux.
  • aux = num1;

Okay, now we do:
  • num1 = num2;

And now how do we get the old value of num1? Just get from the aux:
  • num2 = aux;

Ready, inverted values!
How to swap two variables in C++


See how our code looks:
#include <iostream>
using namespace std;

int main()
{
    int num1, num2, aux;

    cout << "Number 1: ";
    cin >> num1;

    cout << "Number 2: ";
    cin >> num2;

    cout << "\nFirst value: " << num1 <<endl;
    cout << "Second value : " << num2 <<endl;
    cout << "\nSwapping...\n";

    aux = num1;
    num1 = num2;
    num2 = aux;

    cout << "First number : " << num1 <<endl;
    cout << "Second number: " << num2 <<endl;

    return 0;
}

No comments:

Post a Comment