New: 77 pattern programs with tested code in C, C++, Java and Python Explore patterns

Pyramid Patterns

Pyramid patterns are the classic way to practise nested loops. Each row prints a few spaces to push the shape to the centre. Then it prints the characters that build the pyramid. Learn how the spaces and characters change from row to row, and you can print almost any triangle.

Pick a pattern to see its output, a row-by-row diagram and the full program in C, C++, Java and Python.

All 7 pyramid pattern programs

Tips for pyramid patterns

  • Work out how many spaces and how many characters each row needs, and write both as a formula in i.
  • Draw the pattern on paper with row numbers. The formula is usually n − i for spaces and 2i − 1 for characters.
  • Get the full pyramid working first; inverted, hollow and diamond versions are small changes to it.

Frequently asked questions

What is a pyramid pattern program?

It is a program that uses nested loops to print a triangle-shaped figure (a pyramid) of stars, numbers or letters. The outer loop handles rows and the inner loops print the spaces and characters for each row.

How many loops do I need to print a pyramid?

Usually one outer loop for the rows and two inner loops: one for the leading spaces and one for the stars or numbers.

How do I make the pyramid bigger?

Change the value of n. All the formulas depend on n, so the whole shape scales automatically.

More pattern programs