How do I print a right triangle pattern using loops in Java?

You can print a right triangle by increasing the number of stars on each row. Unlike a rectangle, the inner loop limit depends on the current row number.

Source code

Save this example as RightTrianglePatternExample.java.

public class RightTrianglePatternExample {
    public static void main(String[] args) {
        int height = 5;

        for (int row = 1; row <= height; row++) {
            for (int column = 1; column <= row; column++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Explanation

The outer loop counts from 1 through height, including the last row. The inner loop counts from 1 through row. As a result, row 1 contains one star, row 2 contains two stars, and row 5 contains five stars.

The condition column <= row creates the sloping edge. If you replace row with height in that condition, every row contains the same number of stars and the output becomes a square pattern.

For a positive height n, the total number of stars is 1 + 2 + ... + n, which equals n * (n + 1) / 2. This example prints 15 stars.

Run the example

With a JDK installed, open a terminal in the directory containing the source file and run:

javac RightTrianglePatternExample.java
java RightTrianglePatternExample

Output

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

Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here.

Try it yourself

Print an inverted triangle by changing the outer loop to for (int row = height; row >= 1; row--). Keep the inner loop unchanged.

How do I print a rectangle pattern using loops in Java?

To print a rectangle pattern, use separate variables for its height and width. Nested loops let you control the number of rows independently from the number of stars in each row.

Source code

Save this example as RectanglePatternExample.java.

public class RectanglePatternExample {
    public static void main(String[] args) {
        int height = 4;
        int width = 8;

        for (int row = 0; row < height; row++) {
            for (int column = 0; column < width; column++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Explanation

The outer loop uses height, so it produces four rows. The inner loop uses width, so each row contains eight stars. The program prints height * width, or 32, stars.

The inner loop starts again at column = 0 every time the outer loop begins a new row. This reset makes every row the same length.

System.out.print() keeps the stars on the current line, while System.out.println() ends the row. Use positive values for both dimensions to produce a visible rectangle. With these loop conditions, a zero or negative height produces no rows; a positive height and nonpositive width produces blank lines.

Run the example

With a JDK installed, open a terminal in the directory containing the source file and run:

javac RectanglePatternExample.java
java RectanglePatternExample

Output

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

Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here.

Try it yourself

Change height to 6 and width to 3. Observe how changing each loop limit changes a different dimension of the pattern.

How do I print a square pattern using loops in Java?

You can print a square pattern with two nested for loops. The outer loop controls the rows, and the inner loop prints the same number of stars in each row.

Source code

Save this example as SquarePatternExample.java.

public class SquarePatternExample {
    public static void main(String[] args) {
        int size = 5;

        for (int row = 0; row < size; row++) {
            for (int column = 0; column < size; column++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Explanation

The variable size determines both the number of rows and the number of stars per row. With size = 5, the outer loop runs five times. For each row, the inner loop also runs five times, producing 25 stars in total.

System.out.print("* ") prints a star followed by a space without starting a new line. After the inner loop finishes, System.out.println() moves to the next row. Placing that line break inside the inner loop would print each star on a separate line.

The pattern has equal numbers of rows and columns. Its apparent proportions depend on the terminal font and spacing; text cells are not necessarily square.

Run the example

With a JDK installed, open a terminal in the directory containing the source file and run:

javac SquarePatternExample.java
java SquarePatternExample

Output

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

Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here.

Try it yourself

Change size to 3, then to 7. Before running the program, predict how many stars it will print using size * size.

How do I loop through an array in Java?

You can use an enhanced for loop, also called a for-each loop, to read each element in an array.

In this example, you will loop through an array of programming language names and print each name.

Source code

public class ArrayLoopExample {
    void main() {
        String[] languages = {"Java", "Python", "JavaScript"};

        for (String language : languages) {
            IO.println(language);
        }

        IO.println("Total languages: " + languages.length);
    }
}

Explanation

The following statement creates an array containing three strings:

String[] languages = {"Java", "Python", "JavaScript"};

String[] means that the variable holds an array of strings. Each value inside the braces is an element of the array.

The enhanced for loop reads the elements in their array order:

for (String language : languages) {
    IO.println(language);
}

On each iteration, language holds the next element:

Iteration Value of language
1 "Java"
2 "Python"
3 "JavaScript"

The loop ends after processing the last element. You do not need to manage an index or write a condition to stop the loop.

Finally, the program prints the number of elements using the array’s length field:

IO.println("Total languages: " + languages.length);

Use length without parentheses when working with arrays.

Run the example

Compile and run the file:

javac ArrayLoopExample.java
java ArrayLoopExample

Output

Java
Python
JavaScript
Total languages: 3

Use an enhanced for loop when you need to read each element. If you need the position of an element or want to replace values in the array, use an index-based for loop.