#include <stdio.h>
int main() {
int rows;
// Prompt user for the number of rows
printf("Enter the number of rows for the pyramid: ");
scanf("%d", &rows);
// Outer loop for each row
for (int i = 1; i <= rows; i++) {
// Inner loop for printing spaces
for (int j = 1; j <= rows - i; j++) {
printf(" "); // Print space
}
// Inner loop for printing stars
for (int k = 1; k <= (2 * i - 1); k++) {
printf("*"); // Print star
}
// Move to the next line after each row
printf("\n");
}
return 0;
}
Explanation of the Code.
Header Files: The program includes stdio.h
to utilize standard input and output functions.
Getting User Input:
We declare an integer variable rows
to store the number of rows for the pyramid.
We prompt the user to enter the desired number of rows.
Outer Loop:
The outer loop (for (int i = 1; i <= rows; i++)
) runs once for each row of the pyramid.
Inner Loop for Spaces:
The first inner loop (for (int j = 1; j <= rows - i; j++)
) prints spaces to center the stars. The number of spaces decreases as we move down the rows.
Inner Loop for Stars:
The second inner loop (for (int k = 1; k <= (2 * i - 1); k++)
) prints the stars. The number of stars increases as we go down each row, calculated by 2i−12i – 12i−1.
New Line:
After printing the stars for each row, we use printf("\n")
to move to the next line.
Output
Enter the number of rows for the pyramid: 5
*
***
*****
*******
*********