0Pricing
Java Academy · Lesson

Nested For & Text Patterns

Use nested for loops to print rectangles, right triangles, and small tables. Control rows (outer) and columns (inner).

Nested Concept

Nested loops: a loop inside another loop. Often, the outer loop controls rows and the inner loop controls columns.

Rectangle 3x4

Rectangle 3x4

public class Main {
  public static void main(String[] args) {
    // Outer loop controls the number of rows (3 rows total)
    for (int r = 1; r <= 3; r = r + 1) {
      // Start with an empty string for each row
      String line = "";

      // Inner loop controls the number of columns (4 stars per row)
      for (int c = 1; c <= 4; c = c + 1) {
        // Add one star to the line in each iteration
        line = line + "*";
      }

      // Print the completed line of stars
      System.out.println(line);
    }
  }
}

All lessons in this course

  1. For Loop Basics
  2. Nested For & Text Patterns
  3. Pattern Practice & Mini-Challenges
← Back to Java Academy