C Program to Print a Pyramid of Stars

1. Introduction

Creating a pyramid of stars is a fundamental programming exercise, typically used to introduce beginners to the concepts of loops and nested loops in C programming. This simple yet effective program demonstrates how to use loops to systematically print characters (in this case, stars) to form a pyramid shape.

2. Program Steps

1. Ask the user to enter the number of rows for the pyramid.

2. Use a for loop to iterate through each row.

3. Inside the loop, use two more for loops: one to print spaces and another to print stars, thereby forming the pyramid structure.

3. Code Program

#include <stdio.h>

int main() {
    int rows, i, j, space;

    // Prompt user input for the number of rows
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    for(i = 1; i <= rows; i++) {
        // Print spaces before stars in each row
        for(space = 1; space <= (rows - i); space++) {
            printf(" ");
        // Print stars after spaces
        for(j = 1; j <= (2 * i - 1); j++) {
        // Move to the next line after each row is printed

    return 0;


Enter the number of rows: 5


1. The program starts by including the stdio.h library to enable input and output operations.

2. The main function begins execution. It declares integer variables rows for the number of rows in the pyramid, i and j for loop control, and space for printing leading spaces.

3. The user is prompted to enter the number of rows for the pyramid. This input is read and stored in the rows variable.

4. A for loop iterates from 1 to rows, with each iteration representing a row in the pyramid.

5. Inside the loop, another for loop prints spaces. The number of spaces decreases as the row number increases, ensuring the pyramid is centered.

6. Another for loop within the outer loop prints the stars. The number of stars starts at 1 and increases by 2 with each row, forming the pyramid shape.

7. After printing the stars for a row, the program prints a newline character (\n) to move to the next row.

8. This process repeats until all rows have been printed, creating a pyramid shape with stars. The program ends with return 0;, signaling successful completion.