We’ve seen how you can overwrite the value of a variable to change it to another value, and how we can retrieve the value of a variable. Often it is useful to do both things at once. If we have declared a variable named ‘c’, and its value is currently one, then the line:
c = c + 1;
...will add one to the value, and the value will now be 2. In plain English we are saying “make the value of C the same as whatever the value of c currently is, but with 1 added to it”. So whatever the value of C is, the line above will always increase its value by 1. This comes in useful when combined with loops, as we can count how many times we’ve been through the loop. Consider the following code:
int c = 0;
while( c < 10 )
{
//do something
c = c + 1;
}
The code above will do whatever is in the loop exactly 10 times, before continuing with the rest of the program. This is because every time we do the contents of the loop, we then increment the value of c by 1. And when c is equal to 10, c will no longer be less than 10, so the loop will stop.
Write a program that prints out your name exactly 5 times.
Write a program that prints out all the numbers from 10 to 20 (by printing the value of whatever variable you use to keep count).
Change the program so that it only prints out the even numbers from 10 to 20 (hint: one is not the only number you can add).