Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to print pyramid pattern in C
A pyramid pattern is a triangular arrangement of characters (usually stars or numbers) where each row has an increasing number of elements, creating a pyramid-like shape. This is a fundamental pattern printing problem in C programming.
Syntax
for(row = 1; row <= n; row++) {
// Print spaces
for(space = 1; space <= n - row; space++) {
printf(" ");
}
// Print stars
for(star = 1; star <= 2 * row - 1; star++) {
printf("*");
}
printf("<br>");
}
Algorithm
- Accept the number of rows from the user
- For each row from 1 to n −
- Print (n - row) spaces for center alignment
- Print (2 * row - 1) stars for the pyramid shape
- Move to the next line and repeat
Example
Here's a complete program to print a pyramid pattern using stars −
#include <stdio.h>
int main() {
int rows, r, s;
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("\nPyramid Pattern:<br>");
for(r = 1; r <= rows; r++) {
// Print spaces for alignment
for(s = 1; s <= rows - r; s++) {
printf(" ");
}
// Print stars
for(s = 1; s <= 2 * r - 1; s++) {
printf("*");
}
printf("<br>");
}
return 0;
}
Enter number of rows: 5
Pyramid Pattern:
*
***
*****
*******
*********
Key Points
- Each row i has (rows - i) leading spaces and (2 * i - 1) stars
- The pattern is symmetric around the center axis
- Time complexity is O(n²) where n is the number of rows
Conclusion
The pyramid pattern demonstrates nested loops and mathematical relationships in pattern printing. The key is understanding the space-star relationship for proper alignment and shape formation.
Advertisements
