Printing patterns using loops is a common exercise for learning control structures in C. A star pyramid is a symmetrical triangle of stars, with each row containing an increasing number of stars centered horizontally. This program demonstrates how to print a star pyramid using nested loops in C.
Understanding The Problem
The program should take the number of rows as input and print a pyramid of stars. Each row has spaces followed by stars to maintain symmetry. The challenge is to correctly manage the spaces and stars using loops.
Steps to Solve the Problem:
- Take input for the number of rows from the user.
- Use an outer loop to iterate through each row.
- Use an inner loop to print spaces before the stars.
- Use another inner loop to print the stars in each row.
- Move to a new line after printing each row.
Solution: Using Nested Loops
Nested loops allow precise control over the number of spaces and stars in each row.
#include <stdio.h>
int main() {
int rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
for(int i = 1; i <= rows; i++) {
// Print spaces
for(int j = 1; j <= rows - i; j++) {
printf(" ");
}
// Print stars
for(int k = 1; k <= (2 * i - 1); k++) {
printf("*");
}
// Move to the next line
printf("\n");
}
return 0;
}
In this program, the outer loop controls the rows. The first inner loop prints spaces to center the stars, and the second inner loop prints the stars for that row. The expression (2 * i - 1)
ensures the number of stars increases correctly for each row, forming a pyramid.

FAQs
Q1: Can this program create a pyramid with a different character?
Yes, replacing *
with any other character will print the pyramid using that symbol.
Q2: Can we invert the pyramid?
Yes, by adjusting the loops for spaces and stars, you can create an inverted pyramid.
Q3: Can the number of rows be a decimal?
No, the number of rows must be an integer since each row represents discrete stars.
Conclusion
This program demonstrates how to use nested loops to print a star pyramid. By controlling spaces and stars carefully, it creates a symmetrical pattern. The concept can be extended to other patterns like inverted pyramids, diamond shapes, or numeric pyramids.
References & Additional Resources
- C Programming Tutorial – Beginner-friendly tutorials covering loops, nested loops, and pattern printing.
- GeeksforGeeks – Pyramid Pattern in C – Examples of star and numeric patterns using loops.
- TutorialsPoint – C Loops – Explanation of for, while, and nested loops in C.