Star Pattern Programs using Nested For Loops (Python, C, Java)

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

Prints the title, the code in the selected language and the complete pattern.

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

PartJob
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)

iInner loop runsPrinted
11 time*
22 times**
33 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

PatternSpaces in row iStars in row i
Right trianglenonei
Inverted trianglenonen - i + 1
Pyramidn - i2*i - 1
Inverted pyramidi - 12*(n - i) + 1
Squarenonen

Common Mistakes

  1. Forgetting print() after the inner loop, so all stars come in one line.
  2. Starting i at 0 and getting an extra or missing row.
  3. Using the same variable name for both loops.
  4. Wrong indentation in Python, which puts print() inside the inner loop.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top