1.3Loops_in_Java
1.3Loops_in_Java
Loops in Java
Learning Objective
While Loop
A while loop is a control flow statement that allows
code to be executed repeatedly based on a given Boolean
condition. The while loop can be thought of as a repeating
if statement.
// Initialization
while (test condition)
{
// code block to be executed
// increment or decrement (Optional)
}
Do –While Loop
A while loop is a control flow statement that allows
code to be executed repeatedly based on a given Boolean
condition. The while loop can be thought of as a repeating
if statement.
do
{
// code block to be executed
}
while (condition);
For Loop
for loop provides a concise way of writing the loop structure. Unlike a while
loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.
for (Initialization; testing _condition; increment/decrement)
{
// Statements(Code) to be executed
}
Initialization is executed (only ones) before the execution of the code block.
testing condition is the condition for executing the code block.
increment/decrement is executed (every time) after the code block has been
executed.
For-each Loop
The for-each loop is used to traverse array or collection in
Java. It is easier to use than simple for loop because we
don't need to increment value and use subscript notation.
It works on the basis of elements and not the index. It
returns element one by one in the defined variable.
Syntax
for(data_type variable : array_name)
{
//code to be executed
}
Break Statement
It terminate from the loop immediately.
Continue statement
It skips the current iteration of a loop.
Can be used inside any types of loops such as for,
while, and do-while loop.
It will continue the loop but do not execute the
remaining statement after the continue statement.
Quiz
B. while loop
C. do-while loop
D. break statement
B. while loop
C. do-while loop
D. break statement
next iteration
A. return statement
B. continue statement
C. break statement
D. exit statement
B. continue statement
C. break statement
D. exit statement
B. for (traditional)
C. for-each
D. while
B. for (traditional)
C. for-each
D. while
Summary
Practical implementation of for loop.
Thank You