Introduction
Printing a pyramid pattern using stars (*
) is a common exercise in C programming. It helps programmers understand how to use loops, especially nested loops, for formatting output.
Problem Statement
Create a C program that:
- Accepts the number of rows for the pyramid.
- Prints a pyramid using stars (
*
).
Example:
- Input:
rows = 5
- Output:
* *** ***** ******* *********
Solution Steps
- Input the Number of Rows: The size determines how many rows the pyramid will have.
- Use Nested Loops: The outer loop will control the number of rows, while the inner loops will handle printing the spaces and stars.
- Display the Pyramid: Print stars in each row in increasing order, centered with spaces.
C Program
#include <stdio.h>
int main() {
int i, j, rows;
// Step 1: Accept the number of rows for the pyramid
printf("Enter the number of rows: ");
scanf("%d", &rows);
// Step 2: Outer loop for each row
for (i = 1; i <= rows; i++) {
// Step 3: Print spaces for alignment
for (j = i; j < rows; j++) {
printf(" ");
}
// Step 4: Print stars in each row
for (j = 1; j <= (2 * i - 1); 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 pyramid.
Step 2: Outer Loop for Rows
- The outer loop controls how many rows the pyramid will have, running from
1
torows
.
Step 3: Print Spaces for Alignment
- An inner loop is used to print spaces, ensuring that the stars are centered to form the pyramid shape. The number of spaces decreases as the row number increases.
Step 4: Print Stars
- Another inner loop prints the stars (
*
) in each row. The number of stars printed follows the formula2 * i - 1
, which increases by 2 in each subsequent row.
Output Example
For rows = 5
, the output is:
*
***
*****
*******
*********
For rows = 7
, the output is:
*
***
*****
*******
*********
***********
*************
Conclusion
This C program prints a pyramid using stars (*
). The stars are aligned using spaces, and the number of stars increases row by row to create the pyramid shape. This exercise is useful for learning how to handle loops and formatting output in C.
Comments
Post a Comment
Leave Comment