Nearby lessons
50 of 124C - Pattern Programs
Classic C pattern programs — squares, right triangles, pyramids, diamonds, Pascal's triangle and number patterns. Every example uses nested loops, so patterns are the best possible loop practice.
The Universal Pattern Recipe
Every pattern program follows the same three-step structure. Once you see it, all patterns become the same problem:
- Outer loop — one iteration per row.
- Inner loop(s) — print the spaces and symbols for that row.
- Newline — printed in the outer loop, after the inner loop ends.
1. Square of Stars
The simplest case: every row has the same number of columns, so the inner loop does not depend on i.
2. Left-Aligned Right Triangle
Now the inner loop runs to i instead of n, so row 1 gets one star, row 2 gets two, and so on:
3. Inverted Triangle
Count down instead of up — start the inner loop at i and run to n:
4. Pyramid — Spaces Plus Stars
A centred pyramid needs two inner loops: one for the leading spaces (n - i) and one for the stars (2*i - 1):
5. Diamond
A diamond is a pyramid followed by an inverted pyramid. Two outer loops, same formulas:
6. Hollow Square
Print a star only on the border — that is, when the row or column is first or last:
7. Number Patterns
Swap the star for a number. Printing j counts across; printing i repeats the row number:
8. Floyd's Triangle and Alphabet Pattern
Floyd's triangle keeps one counter running across all rows. The alphabet version adds the column number to 'A':
Pattern Formula Cheat Sheet
| Pattern | Spaces on row i | Symbols on row i |
|---|---|---|
| Square | 0 | n |
| Right triangle | 0 | i |
| Inverted triangle | 0 | n - i + 1 |
| Pyramid | n - i | 2*i - 1 |
| Inverted pyramid | i - 1 | 2*(n-i) + 1 |
| Right-aligned triangle | n - i | i |
printf("\n") sits inside the inner loop, every symbol lands on its own line. It belongs in the outer loop, after the inner loop closes.- The outer loop controls rows; the inner loop controls columns.
- Stars in row i is usually i (triangle) or 2*i-1 (pyramid).
- Leading spaces in a pyramid of n rows is n - i.
- Print the newline in the outer loop, after the inner loop finishes.
- Every pattern is just arithmetic on the row number.