Guide to Object-oriented Programming With Java (Buffalo State University Version)
Chapter 9: Using Loops
Java provides a few different control structures that allow you to loop through data using a set of statements.
The Java for
Loop
The for
statement provides a way to loop through a statement, or group of statements, a number of times.
int doubled = i * 2;
System.out.print(i + " * 2 = " + doubled);
}
for
Loop
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
4 * 2 = 9
5 * 2 = 10
for
Loop OutputThe Java for
Loop With an Array
The for
loop statement also provides a way to "walk" through an array.
for (int item:= numbers) {
System.out.print("Count is: " + item);
}
for
Array Loop
Count is: 1
Count is: 2
Count is: 3
for
Array Loop OutuputThe Java while
Loop
The while
loop statement provides a way to to perform a statement or statements based on a condition being true or false.
while (i < 5; i++) {
int doubled = i * 2;
System.out.print(i + " * 2 = " + doubled);
}
while
Loop
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
4 * 2 = 9
5 * 2 = 10
while
Loop OutuputThe Java do / while
Loop
The do ... while
loop statements provide a way to to perform a statement or statements based on a condition being true or false. A do ... while
loop tests the condition at the end of the loop. S, a do ... while
loop will always execute at least once.
do {
int doubled = i * 2;
System.out.print(i + " * 2 = " + doubled);
i++;
} while (i < 5);
do / while
Loop
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
4 * 2 = 9
5 * 2 = 10
do ... while
Loop OutuputLet's get started with a While program!