1. Introduction
Printing patterns in programming often serves as a great way to understand the usage of loops and control structures. In this blog post, we'll focus on creating a C program that prints an inverted pyramid of stars. This simple yet intriguing pattern showcases the fundamental concepts of nested loops in C programming.
2. Program Steps
1. Ask the user to enter the number of rows for the inverted pyramid.
2. Use a loop to iterate from the number of rows down to 1.
3. Inside the loop, implement two more loops: one for printing spaces and another for printing stars.
4. Decrease the number of stars and increase the number of spaces as you move up each row.
3. Code Program
#include <stdio.h>
int main() {
int rows, i, j, space;
// Prompt the user to enter the number of rows
printf("Enter the number of rows: ");
scanf("%d", &rows);
for(i = rows; i >= 1; --i) {
// Print leading spaces
for(space = 0; space < rows - i; ++space)
printf(" ");
// Print stars for each row
for(j = i; j <= 2 * i - 1; ++j)
printf("*");
// Print stars for the left side of pyramid
for(j = 0; j < i - 1; ++j)
printf("*");
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 5 ********* ******* ***** *** *
Explanation:
1. The program starts by including the stdio.h header file for input and output functions.
2. main() function is defined as the entry point of the program.
3. Variables rows, i, j, and space are declared for later use in loops.
4. The user is prompted to enter the number of rows for the inverted pyramid.
5. A for loop is set to iterate from rows down to 1. This loop handles the printing of each row.
6. Inside this loop, a sub-loop prints the leading spaces required to align the stars correctly for the inverted pyramid shape.
7. Another loop prints the stars for each row, where the number of stars decreases as the loop progresses upwards.
8. An additional loop is used to print the right side of the pyramid, ensuring the correct number of stars are printed on each side.
9. Finally, the program ends with return 0;, indicating successful execution.
Comments
Post a Comment