DEV Community

Saravanan
Saravanan

Posted on

Control flow statement: while loop.

loops:

-Loops can execute a block of code as long as a specified condition is reached.
-Loops are handy because they save time, reduce errors, and they make code more readable.

while loop:

A while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop continues to execute as long as the condition evaluates to true.

syntax:

while (condition) {
// code block to be executed
}

task 1:

/*
                int count = 0;
                while(count<=5)
                {                                       //Output:1 1 1 1 1
                    System.out.println(1);
                    count = count + 1;
                }
                */


Enter fullscreen mode Exit fullscreen mode

task 2:

 /*
                int count = 5;
                while(count>=1)
                {                                         //Output:5 4 3 2 1 
                    System.out.println(count);
                    count = count - 1;
                }
                */
Enter fullscreen mode Exit fullscreen mode

key point:

-The loop runs zero or more times, depending on the condition.
-If the condition is false at the start, the loop does not execute.
-If the condition never becomes false, an infinite loop occurs.

Top comments (0)