while ("expression") <"statement(s)"> |
<"expression"> →true <"statement"> ↓ false |
int x = 0;
while (x
< 2){
System.out.println("Hello!");
x++; //increments x, same as x = x +1.
The
do-while-loop has the following syntax.
do{ <"statement(s)"> }while ("expression") |
The do-while
loop is similar to the while-loop. The only difference is that the statement(s)
is executed before the expression is checked to be true or false.
If it is false the next time
around the loop exits, and if it returns true
again the statement(s) is executed.
int x = 0;
do{
System.out.println("Hello!");
x++; //increments x, same as x = x +1.
}while(x < 2);
Output:
Hello!
Hello!
Solution:
The do loop executes the statement the first time around and prints
“Hello!” to the screen, and then increments x to x = 1; Then it
checks the while condition
which is x < 2, it satisfies the
condition to be true, so it
executes the statement again. And
then increments x to x =2; this is
where the while condition
fails because x == 2 the condition is x < 2. So the loop is
terminated at this point.
“The for statement provides a
compact way to iterate over a range of values. Programmers often refer to it as
the "for loop" because of the way in which it repeatedly
loops until a particular condition is satisfied. (citation)”
The for-loop has the following syntax.
for ( initialization; termination; incrementation; ) { <"statement(s)"> } |
<incrementation> <statement(s)> <Initialization> |
Example:
for (int x = 0; x < 10; x++){
System.out.println("Hello!");
}
Output: the for
statement executes ten times because the initial state of x = 0; each
time for statement
checks for the termination
value if it is false or true. It return true ten times before the
termination
state of x < 10
is met. Meaning that “Hello!” is printed ten times to the screen
before the conditions
returns false.
(Alphonce & Decker)
The for-each-loop has the following
syntax.
for ( <Object> <task/identifier>: collection) {<"statement(s)">} |
For-each loop is useful to iterate through a collection. For instance,
String[] numbers = {"1","2","3","4","5"};
for (String
item : numbers) {
System.out.println("String :
" + item);
}
Output:
String
: 1
String
: 2
String
: 3
String
: 4
String
: 5