Lesson 4 | Loop Statements |
Objective | Cover important points about the for, while, and do statements |
For, while, and Do Loop Statements in Java
for statement
The
for
statement is used to repeatedly execute a statement or statement block while an index variable (or set of index variables) is updated. The
for
statement is controlled by a three-part
for
clause that consists of
- initialization statements,
- a
boolean
expression,
- and update statements, which can be an increment or decrement of the variable that was initialized.
The three parts are separated by semicolons:
Always make sure you use the correct condition for what you want to achieve with your loop.
- You want to count from 0 to (n-1):
for( i = 0; i < n ; i++)
- You want to count from 1 to n:
for (i = 1; i <=n ; i++)
Java Reference
for(initializationStatements; booleanExpression;update statements)
statementBlock
Multiple initialization or iteration statements are separated by commas. If multiple statements are contained in the initialization part, then all variables that are declared in the initialization statements must be of the same type.
for (initialization; boolean condition; iterator ) {
/*Nested statement(s) that are repeatedly executed with
each iteration of the for statement.*/
}
The while statement
The while
statement is much simpler than the for
statement. It repeatedly executes a statement block until a boolean
expression becomes false. If the boolean
expression is initially false then the statement block is not executed at all.
while (condition) {
/*Nested statement(s) that are executed
while condition is true.*/
}
The do-while statement
The do
statement is similar to the while
statement but differs in that it executes a statement block first and then evaluates a boolean
expression to determine if the block should continue to be executed. This means that the statement block will execute at least once.
do {
/*Nested statement(s)*/
}
while (condition);