Repetition

All repetition (iteration) structures control:

Repetition statements are also called loops.

The controlled statement(s) are called the loop body.


The while Statement

Repetition is controlled by a continuation condition, tested before the loop body is executed. Its general form is:
   while (condition)
      statement
Effect:


while Example

Compute the sum of the first 50 positive integers:
int sum, num;
...
sum = 0;
num = 1;
while (num <= 50)
    sum = sum + num;


The do..while Statement

Repetition is controlled by a continuation condition, tested after the loop body is executed. Its general form is:
   do {
      statements;
   } while (condition);
Effect:

Use do..while if at least one iteration needed.


The for Statement

The for statement is shorthand for a common pattern of usage of while:
   init;
   while (condition) {
      statements;
      next;
   }
init sets state for first iteration. next sets state for next iteration.

This is expressed using for as:

   for (init; condition; next) {
      statements;
   }
Any of init, condition or next may be omitted.


For Example - A Table of Squares

Print a table of squares.
int i;
...
for (i = 1; i <= 99; i = i + 1) {
    System.out.print(i);
    System.out.print("^2  =  ");
    System.out.println(i*i);
}
which executes as follows
   % java Example
    1^2 = 1
    2^2 = 4
    3^2 = 9
   ...
   10^2 = 100
   ...
   98^2 = 9604
   99^2 = 9801


The break Statement

A break statment must appear within a while,do-while or for loop.

Its execution causes the loop to exit immediately.

It is usually appears in the body of an if statement

This form is common:

   for (init; condition; next) {
      statements1;
      if (condition2)
          break;
      statements2
   }

The break Statement

Simple example of break statement use:
int n, num, count, sum = 0;
... /* infinite loop! */
for (count  = 1 ; ; count = count + 1) {
    printf("Enter a number: ");
    num = Integer.parseInt (stdin.readLine());
    if (num < 0)
    	break; /* non-number -> give up */
    sum = sum + num;
}
System.out.print("Average = ");
System.out.println(sum/count);


The continue Statement

A continue statment must appear within a while,do-while or for loop.

Its execution causes the remainder of the loop body to be skipped - execution skips to the next iteration of the loop.

It is usually appears in the body of an if statement

This form is common:

   for (init; condition; next) {
      statements1;
      if (condition2) continue;
      statements2;
   }

The continue Statement

Simple example of continue statement use:
int n, num, count, sum = 0;
... /* infinite loop! */
for (count  = 1 ; ; count = count + 1) {
    printf("Enter a number: ");
    num = Integer.parseInt (stdin.readLine());
    if (num < 0)
    	break;
    if (num == 0)
    	continue;
    sum = sum + num;
}
System.out.print("Average = ");
System.out.println(sum/count);