Program in C to Print Inverted Pyramid

Program in C to Print Inverted Pyramid

An inverted pyramid is a pattern of stars where the widest row appears at the top and each subsequent row has fewer stars, forming a triangle pointing downward. Printing such patterns is a common exercise to learn nested loops and control of spaces in C.

Understanding The Problem

The program should take the number of rows as input and print an inverted pyramid of stars. Each row must have leading spaces to center the stars properly. Correct management of spaces and stars in nested loops is the key to achieving the pattern.

Steps to Solve the Problem:

  • Take the number of rows as input from the user.
  • Use an outer loop to iterate through each row from top to bottom.
  • Use an inner loop to print spaces at the beginning of each row.
  • Use another inner loop to print stars in each row.
  • Move to a new line after each row.

Solution: Using Nested Loops

Nested loops allow precise control over the number of spaces and stars for each row.

#include <stdio.h>

int main() {

    int rows;

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

    for(int i = rows; i >= 1; i--) {

        // Print leading spaces
        for(int j = 1; j <= rows - i; j++) {
            printf(" ");
        }

        // Print stars
        for(int k = 1; k <= (2 * i - 1); k++) {
            printf("*");
        }

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

    }

    return 0;

}

In this program, the outer loop starts from the maximum row and decrements. The first inner loop prints spaces to center the stars, while the second inner loop prints stars. The formula (2 * i - 1) ensures the correct number of stars in each row, forming the inverted pyramid.

Inverted Pyramid

FAQs

Q1: Can this pattern be printed with a different character?
Yes, you can replace * with any other symbol to print the inverted pyramid.

Q2: Can we combine this with a normal pyramid to form a diamond?
Yes, by printing a normal pyramid first and then the inverted pyramid, you can create a diamond pattern.

Q3: Can the number of rows be a decimal?
No, the number of rows must be an integer, as each row corresponds to a distinct set of stars.

Conclusion

This program demonstrates how to use nested loops to print an inverted star pyramid. By carefully controlling spaces and stars, the pattern appears symmetrical. This concept can be extended to create diamonds, hollow pyramids, and other creative star patterns.

References & Additional Resources

Scroll to Top