Star patterns are the first thing most students learn to understand nested loops. In this post you will learn how the outer loop and inner loop work together, with code in Python, C and Java, a dry run, and an interactive tool where you can watch the loops run step by step.
★ Star Pattern Programs using Nested For Loops
Watch how the outer loop picks the row and the inner loop prints each cell.
Graphical view
Code
Output
Complete output
What is a Nested For Loop?
A nested for loop is a loop placed inside another loop. The outer loop controls the number of rows. For each row, the inner loop runs completely and prints the characters of that row.
How the Logic Works
| Part | Job |
|---|---|
Outer loop (i) | Decides which row we are on |
Inner loop (j) | Prints stars (or spaces) in that row |
print() / printf("\n") | Moves to the next line after each row |
Example 1: Right Triangle Pattern
*
**
***
****
*****
Python
python
n = 5
for i in range(1, n + 1):
for j in range(i):
print("*", end="")
print()
C
c
#include <stdio.h>
int main() {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Java
java
public class Pattern {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
Dry Run (n = 3)
| i | Inner loop runs | Printed |
|---|---|---|
| 1 | 1 time | * |
| 2 | 2 times | ** |
| 3 | 3 times | *** |
Example 2: Pyramid Pattern
*
***
*****
*******
*********
Here each row needs two inner loops: one for spaces (n - i) and one for stars (2*i - 1).
python
n = 5
for i in range(1, n + 1):
for j in range(n - i):
print(" ", end="")
for j in range(2 * i - 1):
print("*", end="")
print()
Quick Formula Table
| Pattern | Spaces in row i | Stars in row i |
|---|---|---|
| Right triangle | none | i |
| Inverted triangle | none | n - i + 1 |
| Pyramid | n - i | 2*i - 1 |
| Inverted pyramid | i - 1 | 2*(n - i) + 1 |
| Square | none | n |
Common Mistakes
- Forgetting
print()after the inner loop, so all stars come in one line. - Starting
iat 0 and getting an extra or missing row. - Using the same variable name for both loops.
- Wrong indentation in Python, which puts
print()inside the inner loop.