Program to print pyramid pattern in C

A pyramid pattern is a triangular arrangement of characters (usually stars or numbers) where each row has an increasing number of elements, creating a pyramid-like shape. This is a fundamental pattern printing problem in C programming.

* * * * * * * * * * * * * * * Pyramid Pattern (5 rows)

Syntax

for(row = 1; row <= n; row++) {
    // Print spaces
    for(space = 1; space <= n - row; space++) {
        printf(" ");
    }
    // Print stars
    for(star = 1; star <= 2 * row - 1; star++) {
        printf("*");
    }
    printf("<br>");
}

Algorithm

  1. Accept the number of rows from the user
  2. For each row from 1 to n −
  3. Print (n - row) spaces for center alignment
  4. Print (2 * row - 1) stars for the pyramid shape
  5. Move to the next line and repeat

Example

Here's a complete program to print a pyramid pattern using stars −

#include <stdio.h>

int main() {
    int rows, r, s;
    
    printf("Enter number of rows: ");
    scanf("%d", &rows);
    
    printf("\nPyramid Pattern:<br>");
    
    for(r = 1; r <= rows; r++) {
        // Print spaces for alignment
        for(s = 1; s <= rows - r; s++) {
            printf(" ");
        }
        
        // Print stars
        for(s = 1; s <= 2 * r - 1; s++) {
            printf("*");
        }
        
        printf("<br>");
    }
    
    return 0;
}
Enter number of rows: 5

Pyramid Pattern:
    *
   ***
  *****
 *******
*********

Key Points

  • Each row i has (rows - i) leading spaces and (2 * i - 1) stars
  • The pattern is symmetric around the center axis
  • Time complexity is O(n²) where n is the number of rows

Conclusion

The pyramid pattern demonstrates nested loops and mathematical relationships in pattern printing. The key is understanding the space-star relationship for proper alignment and shape formation.

Updated on: 2026-03-15T12:37:09+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements