Nested while loop:
- Defining a while loop inside another loop.
- Inner loop executes only if outer loop conditions satisfies.
- Loop terminates only if outer loop condition fails.
Analyze the code:
class Test
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
System.out.print("i : " + i + "\t ---> ");
int j=1;
while(j<=5)
{
System.out.print("j : " + j + "\t");
++j;
}
System.out.println();
++i;
}
}
}
- We can process two dimensional data using nested loops easily.
- Outer loop represents number of rows
- Inner loop represents number of columns.
- Nested loops are used to process Multi dimensional arrays and Printing Patterns.
Simple pattern printing:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
class Test
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
int j=1;
while(j<=5)
{
System.out.print("* ");
++j;
}
System.out.println();
++i;
}
}
}
Pattern printing:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
class Test
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
int j=1;
while(j<=5)
{
System.out.print(j + " ");
++j;
}
System.out.println();
++i;
}
}
}
Printing Combinations:
class Test
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
{
int j=1;
while(j<=5)
{
System.out.print("(" + i + " , " + j + ") ");
++j;
}
System.out.println();
++i;
}
}
}
Output:
(1 , 1) (1 , 2) (1 , 3) (1 , 4) (1 , 5)
(2 , 1) (2 , 2) (2 , 3) (2 , 4) (2 , 5)
(3 , 1) (3 , 2) (3 , 3) (3 , 4) (3 , 5)
(4 , 1) (4 , 2) (4 , 3) (4 , 4) (4 , 5)
(5 , 1) (5 , 2) (5 , 3) (5 , 4) (5 , 5)
class Loops
{
public static void main(String[] args)
{
int i=0;
while(++i<=5)
{
int j=0;
while(++j<=5)
{
System.out.println("(i , j ) : "+i+","+j);
}
}
}
}
Output the code:
class Loops
{
public static void main(String[] args)
{
int i=0, j=0;
while(++i<=5)
{
while(++j<=5)
{
System.out.println("J value : "+j);
}
System.out.println("J value : "+j);
}
}
}
Output it:
class Loops
{
public static void main(String[] args)
{
int i=1, j=1;
while(i++ <= 4)
{
while(j++ <= 3)
{
}
}
System.out.println("final i value : "+i);
System.out.println("final j value : "+j);
}
}