• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

While Loop


While:
'while' is a keyword in java language which is used to execute one block of statements several number of times based on the condition.
Syntax
while(condition)
{
    Statement 1;
    Statement 2;
    ..
    .. 
}
In the above syntax if the condition is true the statements of while block is execute infinite times, if the condition is false while block terminated :


MSK TechnologiesTrainings

Display 1 to 10 Values Using While Loop

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

Output:
1
2
3
4
5
6
7
8
9
10

Display 10 to 1 Values Using While Loop

public class Main
{
    public static void main(String args[])
    {
        int x=10;
        while(x>=1)
        {
            System.out.println(x);
            x--;
        }
    }
}
                                

Output:
10
9
8
7
6
5
4
3
2
1

Nested For While In java


Nested while Loop :
One While loop within another while loop is knows as Nested while Loop Syntax

while(condition)
{
    while(condition)
    {
        Statement 1;
        Statement 2;
        ..
        .. 
    }
    Statement 3;
    Statement 4;
    ..
    .. 
}
In the above syntax :
Outer loop is Row
Inner loop is Column
***
***
***
***
***
***

public class Main
{
    public static void main(String args[])
    {
        int x=1,y;
        while(x<=6)
        {
            y=1;
            while(y<=3)
            {
                System.out.print("*");
                y++;
            }
        System.out.println();
        x++;
        }
    }
}
                                

Output:
***
***
***
***
***
***

*
**
***
****
*****
******

public class Main
{
    public static void main(String args[])
    {
        int x=1,y;
        while(x<=6)
        {
            y=1;
            while(y<=x)
            {
                System.out.print("*");
                y++;
            }
        System.out.println();
        x++;
        }
    }
}
                                

Output:
*
**
***
****
*****
******

******
*****
****
***
**
*

public class Main
{
    public static void main(String args[])
    {
        int x=1,y;
        while(x<=6)
        {
            y=6;
            while(y>=3)
            {
                System.out.print("*");
                y--;
            }
        System.out.println();
        x++;
        }
    }
}
                                

Output:
******
*****
****
***
**
*