While Loop in Java
In this class, We discuss While Loop in Java.
The reader should have prior knowledge of if elseif else statements. Click Here.
Loop: Some thing executed multiple times we call it loop.
A block of code which is needed to be executed multiple times is placed in a loop.
Example:
The below diagram shows the loop example.
while(condition)
if the condition is true then body of the loop is executed.
The statement written between {} is the body of the while loop.
The execution come out of the while loop if the condition is false.
In order to write a loop we need three steps.
1) Initialize a variable.
2) Write the condition
3) Update the variable
First, we initialized the variable i.
i<5 is the condition.
i = i+1 is the updation of the variable.
Output:
1-loop
2-loop
3-loop
4-loop
Out side the loop
The execution continue with remaining statements after coming out of the loop.
Example for better intuition:
In a video game you are provided with five chances.
Once you lost the life again you can play.
Total five chances after that game over.
The below diagram shows the code.
Initialy i =5, because five chances.
In the loop after loosing the chance decrement i.
contion i>0 will exit from the loop after five chances.