Java ProgramsPatternsPrint Rectangle Star Pattern

Print Rectangle Star Pattern in Java

beginner·  Patterns  ·  Star Patterns

Problem

A rectangle pattern generalizes the square pattern by giving the row count and column count their own separate variables instead of sharing one.

Given a number of rows and a number of columns, print a solid rectangle of stars that size.

Input
rows = 4, cols = 6
Output
* * * * * * * * * * * * * * * * * * * * * * * *

Java Program

Java
public class RectangleStarPattern { public static void main(String[] args) { int rows = 4, cols = 6; for (int i = 0; i < rows; i++) { StringBuilder row = new StringBuilder(); for (int j = 0; j < cols; j++) { if (row.length() > 0) row.append(" "); row.append("*"); } System.out.println(row); } } }

Output

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

Core Logic

Using two separate variables for the row count and the column count, instead of one shared size, lets the grid be any shape instead of only a square.

How It Works
  1. 1The outer for (int i = 0; i < rows; i++) runs once per row.
  2. 2The inner for (int j = 0; j < cols; j++) runs cols times on every row, independent of rows.
  3. 3A separating space is added before every star except the first in a row, avoiding a trailing space.
  4. 4Since neither loop bound depends on the other, rows and cols can be set to different values freely.
For rows = 4 and cols = 6, every one of the 4 rows prints 6 stars, producing a 4-by-6 block.
💡

Key Point: The only change from a solid square is using two variables instead of one — the loop structure itself is identical.

Complexity
Time Complexity: O(rows × cols)Space Complexity: O(1)

Why: The nested loop visits every one of the rows times cols grid positions once, with no growing storage.

Key Concepts

nested for loopindependent dimensions

Related Programs