The for Statement - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript The for Statement - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, March 25, 2019

The for Statement

The for Statement

üThe for statement has the following syntax:

The for Statement


üA for loop is functionally equivalent to the following while loop structure:

initialization;
while (condition) {
    statement;
    increment;
}

Logic of a for loop

The for Statement

üLike a while loop, the condition of a for statement is 
tested prior to executing the loop body
üTherefore, the body of a for loop will execute zero or more 
times
üIt is well suited for executing a loop a specific number of 
times that can be determined in advance
for Example
final int LIMIT = 5;

for (int count = 1; count <= LIMIT; count++) {

    System.out.println(count);

}

Output:

1
2
3
4
5

The for Statement

üEach expression in the header of a for 

loop is optional


üIf the initialization is left out, no

 initialization is performed


üIf the condition is left out, it is always

 considered to be true, and therefore

 creates an infinite loop


üIf the increment is left out, no increment

 operation is performed


üBoth semi-colons are always required in 

the for loop header


Choosing a Loop Structure


üWhen you can’t determine how many
 times you want to execute the loop
 body, use a while statement or a do 
statement

üIf it might be zero or more times,
 use a while statement

üIf it will be at least once, use a do
 statement

üIf you can determine how many times
 you want to execute the loop body, use
 a for statement


No comments:

Post a Comment

Post Top Ad