Looping Statements
Looping Statements
• Java provides three ways for executing the loops. While all
the ways provide similar basic functionality, they differ in
their syntax and condition checking time.
→While loop
→Do while loop
→For loop
While loop :
• 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.
Syntax:
while (test_expression)
{
// statements
update_expression;
}
The various parts of the While loop are:
1.Test Expression: In this expression we have to test the condition. If the
condition evaluates to true then we will execute the body of the loop and go to
update expression.
Otherwise, we will exit from the while loop.
Example: i <= 10
Example: i++;
Flow chart while loop (for Control Flow):
• Example : this program will print numbers from 1 to 10
class whileLoopDemo
{
public static void main(String args[])
{
// initialization expression
int i = 1;
// test expression
while (i < =10)
{
System.out.println(i);
// update expression
i++;
}
}
}
Do while loop :
• do-while loop is an Exit control loop. Therefore, unlike for or while loop,
a do-while check for the condition after executing the statements or the loop
body.
Syntax:
do
{
// statements
update_expression ;
}
while (test_expression);
Flowchart do-while loop:
• Example : this program will print numbers from 1 to 10
class dowhileloopDemo
{
public static void main(String args[])
{
// initialisation expression
int i = 1;
do {
// Print the statement
System.out.println(i);
// update expression
i++;
}
// test expression
while (i <=10);
}
}
Difference between while and do while loop:
while do-while
• Condition is checked first then statement(s) is • Statement(s) is executed at least once,
executed. thereafter condition is checked.
• while loop is entry controlled loop. • do-while loop is exit controlled loop.
For loop :
• for loop provides a concise way of writing the loop structure. The for
statement consumes the initialization, condition and increment/decrement in
one line thereby providing a shorter, easy to debug structure of looping.
Syntax:
Example: i <= 10
3. Update Expression: After executing the loop body, this expression
increments/decrements the loop variable by some value.
Example: i++;
Flow chart for loop (For Control Flow):
• Example : this program will print numbers from 1 to 10
class forLoopDemo
{
public static void main(String args[])
{
// Writing a for loop