C Program to Print Stars in Pyramid Shape

1. Introduction

In the realm of programming, printing patterns using loops is a common exercise that helps beginners grasp the concepts of looping constructs. One such popular pattern is the star pyramid. In this guide, we will explore how to write a C program to print stars in a pyramid shape.

2. Program Overview

1. Ask the user to input the height of the pyramid.

2. Use nested loops:

- The outer loop controls the number of rows.

- The first inner loop prints spaces.

- The second inner loop prints stars.

3. Print the pyramid on the screen.

3. Code Program

#include <stdio.h>

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

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

    for(i = 1; i <= rows; i++) {
        // Print spaces in pyramid
        for(space = 1; space <= rows - i; space++) {
            printf(" ");
        }

        // Print stars in pyramid
        for(j = 1; j <= (2 * i - 1); j++) {
            printf("*");
        }

        // Move to the next line
        printf("\n");
    }

    return 0;
}

Output:

Enter number of rows for the pyramid: 5
    *
   ***
  *****
 *******
*********

4. Step By Step Explanation

1. The user is prompted to input the height (number of rows) of the pyramid.

2. An outer loop runs from i = 1 to the number of rows. This loop is responsible for printing each row of the pyramid.

3. The first inner loop prints spaces before the stars in each row. The number of spaces decreases as we go down the rows.

4. The second inner loop prints stars. In the first row, one star is printed, in the second row, three stars, and so on. The pattern follows 2 * i - 1 for each row.

5. After printing the spaces and stars for each row, the program moves to the next line using the printf("\n") statement.

Comments