C Program to Print an Inverted Pyramid Pattern

Introduction

An inverted pyramid pattern is where the number of stars (*) decreases as you go down each row. This type of pattern helps beginners in C programming to understand nested loops and control structures.

Problem Statement

Create a C program that:

  • Accepts the number of rows for the inverted pyramid.
  • Prints an inverted pyramid using stars (*).

Example:

  • Input: rows = 5
  • Output:
    *********
     *******
      *****
       ***
        *
    

Solution Steps

  1. Input the Number of Rows: The size determines how many rows the inverted pyramid will have.
  2. Use Nested Loops: The outer loop controls the number of rows, while the inner loops handle printing spaces and stars.
  3. Display the Inverted Pyramid: Print stars in decreasing order row by row, with leading spaces to align the pyramid properly.

C Program

#include <stdio.h>

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

    // Step 1: Accept the number of rows for the inverted pyramid
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    // Step 2: Outer loop for the rows
    for (i = rows; i >= 1; i--) {
        // Step 3: Print spaces for alignment
        for (j = rows; j > i; j--) {
            printf(" ");
        }

        // Step 4: Print stars in each row
        for (j = 1; j <= (2 * i - 1); j++) {
            printf("*");
        }

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

    return 0;
}

Explanation

Step 1: Input Number of Rows

  • The program starts by accepting input from the user, which defines the number of rows in the inverted pyramid.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed, starting from the largest number of stars and decreasing.

Step 3: Print Spaces for Alignment

  • For each row, the first inner loop prints the necessary spaces to align the stars. The number of spaces increases as you go down the rows.

Step 4: Print Stars

  • The second inner loop prints stars in each row. The number of stars printed follows the formula 2 * i - 1, which decreases as the row number decreases, creating an inverted pyramid.

Output Example

For rows = 5, the output will be:

*********
 *******
  *****
   ***
    *

For rows = 7, the output will be:

*************
 ***********
  *********
   *******
    *****
     ***
      *

Conclusion

This C program prints an inverted pyramid using stars (*). The number of stars decreases row by row, while spaces are used for alignment. This exercise is a good way to practice working with loops and formatting output in C.

Comments