4. Variables

Modifying Variables

Unlike variables in mathematics, those in programming can change their value. In other words, a variable can be assigned a new value any number of times. As the first example of this, we will show how to increment the value of a variable by one.

First, let us introduce a new variable and name it a:

double a=4;

The value of variable a is 4. Now, let us increment a by one:

a++;

After executing this statement, the value of a will be 5.

Besides incrementing a variable, another way to change the value of a variable is simply by assigning it a new value:

a = 9-2;

By executing this statement, the value of a will now be 7. Therefore, this statement assigns a new value to the variable a.

Let us unify all of this into a complete program:

#include <iostream>
using namespace std;

int main()
{
    double a=4;
    cout << "a: " << a << endl;
    a++;
    cout << "a: " << a << endl;
    a = 9-2;
    cout << "a: " << a << endl;
}

Executing this program will result in the following output:

a: 4
a: 5
a: 7

You can't introduce two variables with the same name.[*] Thus, you cannot add this statement at the end of the given program:

    double a = 3;

because this statement attempts to introduce the variable a again.

For the same reason, you cannot modify the next-to-last statement of this program to:

    double a = 9-2;