Sei sulla pagina 1di 9

Loops in Java

(for, while, do-while looping)


Loops in Java

Are designed to perform a specific task


repeatedly. There are many types of loops
available in Java to perform a task. Here, we will
discuss do-while, while, for loops with syntaxes
and examples. A beginner must know the
concept of loops. This is the fundamental
concept of programming.
What are Loops in Java

 Java is Multi-featured language, loops are a way to run


a particular instruction or function a number of times.
Loops are basically used to perform a particular task
repeatedly. Any kind of iteration in programming is done
with the help of loops.
 Java has 3 ways of executing the loops, they are all
nearly similar, with some syntax and condition checking
differences.
1. While loop in Java

 In Java, while loop is continuously executed if the Boolean condition


becomes true, it can be considered as a repeating if statement. While loop
first checks the body of the loop then it will be executed.
 The syntax of Java While Loop –

while (boolean condition)


{
loop statements…
}
While loop is an entry controlled loop,
 the condition is tested before the loop.
 The condition is tested and the iteration follows until the condition becomes false, and
that marks the end of the loop.

If true

START Condition Statement


Checking

If false

End
2. For loop in Java

 Java for loop is a concise version of while loop, it provides the user to write
the whole condition, i.e. initialization, condition and increment/decrement
in one line.
 The Syntax of Java for Loop
for (initialization condition; testing condition; increment/decrement
{
statements (s)
}
A for loop in java is also an entry controlled loop,

 First we initialize the variables in use and then the condition is tested, and accordingly,
increment or decrement takes place.

Increment/
Decrement

If true
Condition
Initialization Checking Statement
START

If false

END
3. Do While Loop in Java
 A do while statement is an exit controlled loop,
 It checks the condition after the execution of the loop. It means that the
body of the loop is executed once if the condition is true or false.

 Syntax of Java do-while loop


do
{
statements……
}
while (condition);
DO WHILE LOOP

If true

Condition
START Statement Checking

If false

END

Potrebbero piacerti anche