Patterns and small projects · beginner
C Program to Print a Star Pattern (Pyramid)
Print star patterns in C with nested for loops: a right triangle, a centred pyramid and an inverted triangle, and work out the spaces and stars for each row.
- nested for loops
- printf and putchar
- loop counters
- rows and columns
Pattern programs are a staple of C exams because they test whether you can turn a picture into loop counters. The outer loop counts rows; inner loops print the spaces and stars for one row.
For a pyramid of 5 rows, row i (from 1) has 5 - i leading spaces and 2 × i - 1 stars.
The program
#include <stdio.h>
int main(void) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++)
putchar('*');
putchar('\n');
}
putchar('\n');
for (int i = 1; i <= rows; i++) {
for (int s = 0; s < rows - i; s++)
putchar(' ');
for (int j = 0; j < 2 * i - 1; j++)
putchar('*');
putchar('\n');
}
return 0;
}*
**
***
****
*****
*
***
*****
*******
*********How it works
- The first outer loop counts rows 1 to 5; its inner loop prints i stars, giving a right triangle.
- putchar('\n') ends each row.
- For the pyramid, the first inner loop prints rows - i spaces to centre the row.
- The second inner loop prints 2 × i - 1 stars: 1, 3, 5, 7, 9.
Another way: Inverted triangle with spaces between stars
Counting the outer loop down instead of up turns the triangle upside down.
#include <stdio.h>
int main(void) {
for (int i = 4; i >= 1; i--) {
for (int j = 1; j <= i; j++)
printf(j < i ? "* " : "*");
printf("\n");
}
return 0;
}* * * *
* * *
* *
*Common mistakes
- Forgetting the newline after the inner loop, which prints every star on one line.
- Using the same loop variable for the inner and outer loop.
- Off-by-one errors in the bounds (j < i versus j <= i), which add or drop a star on every row.
Try it yourself
- Print a diamond: the pyramid followed by an inverted pyramid.
- Print Floyd's triangle (1; 2 3; 4 5 6; …).
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.