Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

The while loop

Same as for loop, while loop is used to execute specific part of the program repeatedly.

Syntax

while(condition)
{
    // programming
    // statements
}

Flowchart

Java Programming Language while loop Flowchart

Working

Java Programming Language while loop Working

Step I –
            Program control checks the condition before entering the while loop.

Step II –
            If the condition is true, control is allowed to enter and execute the body of while loop.

Step III –
            After executing while loop body, control is transferred back again to check the condition.

If the condition is true, again Step-II & Step-III are repeated.

This process goes on till condition does not become false.

To make condition false, we need to write some expression inside the body of while loop.

Example No. 1

class WhileLoopDemo1 
{
    public static void main(String args[])
    {
        int n;
        n = 1;
        while(n<=10)
        {
            System.out.println("John");
            n++;
        }	
    }
}

Output

John
John
John
John
John
John
John
John
John
John

Thus with the help of while loop in the above program, we have succeeded to print name 10 times by writing it just 1 time.

Example No. 2

class WhileLoopDemo2 
{
    public static void main(String args[])
    {
        int n;
        n = 1;
        while(n<=10)
        {
            System.out.print(n+" ");
            n++;
        }	
    }
}

Output

1 2 3 4 5 6 7 8 9 10

Here we have succeeded to print numbers 1 to 10 by writing line

System.out.print(n+" ");

in while loop, just one time.

 

Leave a reply