go to previous page   go to home page   hear noise   go to next page


The most frequently performed operation is adding one to a variable.

Adding One

Most programs have many loops in them and most loops are controlled by a variable which counts the number of times the loop has executed. Each time the loop executes, one is added to the variable. Also, there are many other situations where one is added to a variable. Computer engineers have observed many executing programs and have found that adding one to a variable is the most frequently executed operation. All processor chips have been designed to make this operation very, very fast.

You already know how to add one to a variable:

counter = counter + 1 ;  // add one to counter

This is easy enough, but since it is so common there is a shorter way to do it:

counter++ ;  // add one to counter

This statement uses the postfix increment operator ++. It adds one to the value in counter. The word postfix means that the operator follows its operand. (There is also a prefix operator, which we will see shortly.) Here is a counting loop:

int counter=0;

while ( counter < 10 )
  System.out.println("counter is now " + counter );


Fill in the blank so that the loop prints 0 through 9. Use the increment operator.