C Example Code2026-03-252 min read
Learn how to print star patterns in C: right-angled triangle, inverted pyramid, and diamond shapes using nested loops with full code.
Understanding Nested Loops for Patterns
Printing star patterns in C reinforces understanding of nested loops. The outer loop controls the rows, while inner loops control spacing and character printing across columns.
1. Right-Angled Star Triangle
c (ISO Standard)#include <stdio.h> void printRightTriangle(int rows) { for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { printf("* "); } printf("\n"); } }
2. Centered Pyramid Pattern
c (ISO Standard)#include <stdio.h> void printPyramid(int rows) { for (int i = 1; i <= rows; i++) { /* Print leading spaces */ for (int space = 1; space <= rows - i; space++) { printf(" "); } /* Print odd number of stars: (2*i - 1) */ for (int k = 1; k <= (2 * i - 1); k++) { printf("* "); } printf("\n"); } }
3. Diamond Star Pattern
c (ISO Standard)#include <stdio.h> void printDiamond(int n) { /* Upper half of diamond */ for (int i = 1; i <= n; i++) { for (int j = 1; j <= n - i; j++) printf(" "); for (int j = 1; j <= 2 * i - 1; j++) printf("*"); printf("\n"); } /* Lower inverted half */ for (int i = n - 1; i >= 1; i--) { for (int j = 1; j <= n - i; j++) printf(" "); for (int j = 1; j <= 2 * i - 1; j++) printf("*"); printf("\n"); } } int main() { int n = 4; printf("Centered Star Pyramid (n=%d):\n", n); printPyramid(n); printf("\nStar Diamond Pattern (n=%d):\n", n); printDiamond(n); return 0; }
Sample Output
text (ISO Standard)Centered Star Pyramid (n=4): * * * * * * * * * * * * * * * * Star Diamond Pattern (n=4): * *** ***** ******* ***** *** *
Complexity Analysis
- Time Complexity:
O(n²)quadratic time across row and column iterations. - Space Complexity:
O(1)zero extra memory allocations.
Related Programs
- Explore numerical grids in Number Pattern Programs in C.
- Try combinatorial printing in Pascal's Triangle in C.