Introduction
A reverse pyramid pattern is a triangular arrangement of stars (*
) that starts with a full row of stars and decreases by one star in each subsequent row, forming an inverted pyramid. This exercise helps in understanding how to use nested loops and control the number of spaces and stars.
Problem Statement
Create a C program that:
- Accepts the number of rows for the reverse pyramid.
- Prints a reverse pyramid pattern using stars (
*
).
Example:
- Input:
rows = 5
- Output:
***** **** *** ** *
Solution Steps
- Input the Number of Rows: The size determines how many rows the reverse pyramid will have.
- Use Nested Loops: The outer loop controls the rows, and the inner loops handle printing spaces and stars.
- Display the Reverse Pyramid: Print stars in decreasing order while printing spaces to align the stars.
C Program
#include <stdio.h>
int main() {
int i, j, rows;
// Step 1: Accept the number of rows for the reverse pyramid
printf("Enter the number of rows: ");
scanf("%d", &rows);
// Step 2: Outer loop for rows
for (i = 0; i < rows; i++) {
// Step 3: Print spaces for alignment
for (j = 0; j < i; j++) {
printf(" ");
}
// Step 4: Print stars in decreasing order
for (j = 0; j < (rows - i); j++) {
printf("*");
}
// Move to the next line after printing each row
printf("\n");
}
return 0;
}
Explanation
Step 1: Input Number of Rows
- The program starts by asking the user to input the number of rows for the reverse pyramid.
Step 2: Outer Loop for Rows
- The outer loop controls how many rows will be printed. It runs from
0
torows - 1
.
Step 3: Print Spaces for Alignment
- The first inner loop prints spaces to align the stars properly. The number of spaces increases with each row, ensuring the pyramid remains centered.
Step 4: Print Stars in Decreasing Order
- The second inner loop prints stars (
*
) in decreasing order. The number of stars decreases by one for each row.
Output Example
For rows = 5
, the output will be:
*****
****
***
**
*
For rows = 6
, the output will be:
******
*****
****
***
**
*
Conclusion
This C program prints a reverse pyramid pattern using stars (*
). The program uses nested loops to control the number of spaces and stars, ensuring the stars are printed in decreasing order to form the inverted pyramid. This exercise helps in practicing loops and formatting output in C programming.
Comments
Post a Comment
Leave Comment