Repetition statements are also called loops.
The controlled statement(s) are called the loop body.
while (condition)
statement
Effect:
int sum, num;
...
sum = 0;
num = 1;
while (num <= 50)
sum = sum + num;
do {
statements;
} while (condition);
Effect:
Use do..while if at least one iteration needed.
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.
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
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
}
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);
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;
}
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);