Loops
for
Loops
These are used to repeat a block of code a fixed number of times:
for (initialisation;
condition;
update) {
// stuff to repeat
}
Example
Print the first 10 integers:
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
In this case the {}
aren’t required as a single line statement is a block.
while
Loops
while(condition) {
// stuff to repeat
}
The condition is tested before running the loop. do
while
loops check after.
Example
This program adds integers until the user types 0:
//import java.util.Scanner;
Scanner input = new Scanner();
int total = 0;
int value = input.nextInt();
while (value != 0) {
total += value;
value = input.nextInt();
}
System.out.println(total);