Google News
logo
C Program To Print Hollow Star Pyramid
In the following example of C program to print a hollow star pyramid :
Program :
#include <stdio.h>

int main() {
    int rows;

    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= rows - i; j++) {
            printf(" ");
        }
        for (int j = 1; j <= 2 * i - 1; j++) {
            if (i == rows || j == 1 || j == 2 * i - 1) {
                printf("*");
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }

    return 0;
}
Output :
Enter the number of rows: 7

      *
     * *
    *   *
   *     *
  *       *
 *         *
*************
Explanation :

* We start by declaring a variable rows to store the number of rows in the hollow star pyramid.

* We ask the user to enter the number of rows using printf and scanf.

* We use a for loop to print the hollow star pyramid. The loop runs from 1 to rows, and each iteration of the loop prints one row of the pyramid.

* Inside the loop, we use another for loop to print the spaces before the stars. The number of spaces to be printed in each row is equal to rows - i.

* After printing the spaces, we use a third for loop to print the stars and spaces in the row. The number of characters to be printed in each row is equal to 2 * i - 1.

* We use an if statement to check if we are at the first or last row or if we are at the beginning or end of the row, in which case we print a star. Otherwise, we print a space.

* After printing the characters, we print a newline character using printf to move to the next row of the pyramid.

* After the outer loop, we return 0 to indicate successful execution of the program.