While Loop (Part 4)
While Loop
The
while
loop loops through a block of code as long as a specified condition is true , as soon as block of code fails the condition of while
loop , it exits out of loop.While loop is also an entry controlled group.
➤We use For Loop when we know the number of times the loop needs to be executed , while while loop is used when we dont know the number of times the loop needs to be executed.
The working of both loops is similar.
Syntax:-
while (condition) {
// code block to be executed
}
Flowchart:-
public class MyClass {
public static void main(String args[]) {
int age = 12;
while (age<=18)
{
System.out.println("Age is: "+age);
age++;
}
}
}
Output:-
Age is: 12
Age is: 13
Age is: 14
Age is: 15
Age is: 16
Age is: 17
Age is: 18