next up previous
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:

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 up previous
Next: The for loop Up: Unit 06 Previous: Other loop statements