Loop Control อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 8
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:
Java programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail. Loop TypeDescription while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable. do...while loopLike a while statement, except that it tests the condition at the end of the loop body
While Loop while A while loop statement in java programming language repeatedly executes a target statement as long as a given condition is true. Syntax : while(Boolean_expression) { //Statements }
While Loop : Flow Diagram
While Loop : Example
for loop for A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Syntax: for(initialization; Boolean_expression; update) { … }
for loop : Flow Diagram
for Loop : Example
do while loop do...while A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax: do { //statements }while(Boolean_expression);
do while loop : Flow Diagram
do while Loop : Example
Loop Control Statements : Control StatementDescription break statementTerminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
break statement When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement
break statement Syntax: break; Flow Diagram
break : Example
continue statement In a for loop, the continue keyword causes control to immediately jump to the update statement. In a while loop or do/while loop, control immediately jumps to the Boolean expression.
break statement Syntax: continue; Flow Diagram
Continue : Example
Enhanced for loop in Java: As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays. Syntax: for(declaration : expression){ //statement }
Example
Q&AQ&A The End