Next: The for loop Up: Unit 06 Previous: Other loop statements

Loop controlled by a counter

A common use of loops is the one in which the loop makes use of a variable (called control variable) that at each iteration is changed by a constant value, and whose value determines the end of the loop.

Example: Print the squares of the integers between 1 and 10.

```int i = 1;
while (i <= 10) {
System.out.println(i * i);
i++;
}
```

The following are the common features of loops controlled by a counter:

• a control variable for the loop is used (also called counter or indix of the loop)
E.g., i
• initialization of the control variable
E.g., int i = 1;
• increment (or decrement) of the control variable at each iteration
E.g., i++;
• test if we have reached the final value of the control variable
E.g., (i <= 10)

The for statement loop allows to specify all these operations in a simple way:

Example: Print the squares of the integers between 1 and 10 using a for loop.

```for (int i = 1; i <= 10; i++)
System.out.println(i * i);
```

Next: The for loop Up: Unit 06 Previous: Other loop statements