1. Introduction
Creating patterns with C programming is a fun and educational way to get familiar with loops and conditionals. In this tutorial, we're going to write a C program that prints a hollow pyramid. This pattern is interesting because it combines the concepts of printing spaces and stars to form a pyramid shape, but with a twist: the inside of the pyramid is hollow.
2. Program Steps
1. Request the number of rows for the pyramid from the user.
2. Use a loop to handle the printing of each row.
3. Inside the loop, use conditional statements to print spaces for alignment and stars to create the pyramid outline.
4. Ensure that the inside of the pyramid remains hollow by printing spaces between the stars, except for the base of the pyramid.
3. Code Program
#include <stdio.h>
int main() {
int rows, i, j;
// Asking for user input
printf("Enter the number of rows: ");
scanf("%d", &rows);
for(i = 1; i <= rows; i++) {
// Printing spaces
for(j = i; j < rows; j++) {
printf(" ");
}
// Printing stars for the first row (top of the pyramid) and the last row (base of the pyramid)
for(j = 1; j <= (2 * i - 1); j++) {
if(i == rows || j == 1 || j == (2 * i - 1)) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 5 * * * * * * * *********
Explanation:
1. The program includes the stdio.h library to use the printf and scanf functions.
2. In the main function, rows, i, and j are declared as integers.
3. The user is prompted to input the number of rows for the pyramid.
4. A for loop iterates over each row from 1 to the number of rows entered.
5. Inside this loop, another loop prints the required number of spaces to align the pyramid correctly.
6. A nested loop is then used to print stars and spaces. Stars are printed at the beginning and end of each row, and for every position in the last row, creating the hollow effect inside the pyramid.
7. The program completes execution and returns 0, indicating successful completion.
Comments
Post a Comment