Pattern Practice & Mini-Challenges
Practice nested loop patterns: hollow rectangles, centered pyramids, and diagonals. Tackle mini-challenges step by step.
Pattern Tips
Tips for text patterns:
- Outer loop controls rows
- Inner loop builds each row
- Append characters to a String then print once
- Use conditions to choose star or space
Hollow Rectangle
Hollow rectangle 3x5
public class Main {
public static void main(String[] args) {
// Outer loop: goes through each row (1 to 3)
for (int r = 1; r <= 3; r = r + 1) {
String line = "";
// Inner loop: goes through each column (1 to 5)
for (int c = 1; c <= 5; c = c + 1) {
// Print a star if we are on:
// - the first row (r == 1)
// - the last row (r == 3)
// - the first column (c == 1)
// - the last column (c == 5)
if (r == 1 || r == 3 || c == 1 || c == 5) {
line = line + "*";
} else {
// Otherwise, print a space (inside of the rectangle)
line = line + " ";
}
}
// Print the completed row
System.out.println(line);
}
}
}
All lessons in this course
- For Loop Basics
- Nested For & Text Patterns
- Pattern Practice & Mini-Challenges