Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Nested Loops (Nested for , Nested While, Nested do-while)

Posted By: Decha Boonliang     Category: Java     Views: 30798

This article explains about nested loops in java with examples.

When the body of one loop contains another, the second is said to be nested inside the first.

Any of java's loops can be nested within any other loop. For example

Syntax of Nested Loops

Form 1 :

for(initialization; test; increment)
{
statements;
while(expression)
{
statements;
|
|
|
do
{
statements;
}while(expression);
}
}


Form 2:

for(initialization; test; increment)
{
statements;
for(initialization; test; increment)
{
statements;
|
|
|
for(initialization; test; increment)
{
statements;
}
}
}


Form 3:

While(expression)
{
statements;
|
|
|
While(expression)
{
statements;
}
}

Examples of Nested Loop

Example 1 : Program to display triangle of * using nested for loop

class NestedForLoopDemo
{
  public static void main(String args[])
  {
for(int i = 1; i <=5 ; i++)
{
for(int j = 1; j <= i; j++)
{
System.out.println("* ");
}
System.out.println("");
}
  }
}


Output

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

Example 2 : Program to print tables

class NestedWhileLoop
{
  public static void main(String args[])
  {
int i=1, j=1; 
System.out.println("Tables");

while(i <= 2) // change to 2 to 10 or 20 as many tables user want
{
while(j <= 10)
{
System.out.println(i + " * " + j + " = " + (i*j));
j++;
}
i++;
System.out.println("");
System.out.println("");
}
  }
}


Output

Tables
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10


2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Example 3 : Program to print triangle of numbers

class NestedDOWhileLoop
{
  public static void main(String args[])
  {
int i=1, j=1;
do
{
k = 3;
do
{
        System.out.println(" ");
k--;
}while(k>=i);
j = 1;
do
{
System.out.println(i + " ");
j++:
}while(j<=i);

System.out.println("");
i++;

        }while(i<=5); 

  }
}


Output

     1 
    2 2 
   3 3 3 
  
Share: 

 
 
 


Decha Boonliang
Decha Boonliang author of Nested Loops (Nested for , Nested While, Nested do-while) is from Bangkok, Thailand.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!