Java Nested for Loops Example

Java Nested for Loops Example demonstrates how to use nested for loops in Java with an example.

If we have a for loop inside another for loop, it is known as nested for loop. The inner loop executes completely whenever the outer loop executes.

Nested for Loops

Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops:
package net.javaguides.corejava.controlstatements.loops;

public class NestedForLoops {
    public static void main(String args[]) {
        int i, j;
        for (i = 0; i < 10; i++) {
            for (j = i; j < 10; j++)
                System.out.print(".");
            System.out.println();
        }
    }
}
Output:
..........
.........
........
.......
......
.....
....
...
..
.

Java Nested for Loops More Examples

Pyramid Example 1

public class PyramidExample {

    public static void main(String args[]) {

        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println(); // new line
        }
    }
}
Output:
* 
* * 
* * * 
* * * * 
* * * * * 

Pyramid Example 2


public class PyramidExample {

    public static void main(String[] args) {
        int term = 6;
        for (int i = 1; i <= term; i++) {
            for (int j = term; j >= i; j--) {
                System.out.print("* ");
            }
            System.out.println(); // new line
        }
    }
}
Output:
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

Triangle Pyramid Example 3

package net.javaguides.corejava.arrays.programs;

public class TrianglePyramid {

    public static void main(final String[] args) {
        trianglePyramid(10);
    }

    public static void trianglePyramid(final int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
Output:
*
**
***
****
*****
******
*******
********
*********
**********




Comments