Google News
logo
C Program For Printing Inverted Pyramid
In the following example of C program to print an inverted pyramid :
Program :
#include <stdio.h>

int main() {
    int rows;

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

    for (int i = rows; i >= 1; i--) {
        for (int j = 1; j <= rows - i; j++) {
            printf(" ");
        }
        for (int j = 1; j <= 2 * i - 1; j++) {
            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 inverted pyramid.

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

* We use a for loop to print the inverted pyramid. The loop runs from rows to 1, 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 in the row. The number of stars to be printed in each row is equal to 2 * i - 1.

* After printing the stars, 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.