C Program to print Pattern 8 * *** ***** *** *
Objective
Write a C program to print a Diamond pattern of stars.
Algorithm / Approach
- A diamond is just a regular pyramid placed on top of an inverted pyramid.
- Top half: Loop
ifrom 1 ton. Print spaces (decreasing), then print stars (2*i - 1). - Bottom half: Reset space counter. Loop
ifrom 1 ton-1. Print spaces (increasing), then print stars (2*(n-i) - 1).
main.c
#include<stdio.h>
int main( ) {
int i, j,n,space;
scanf("%d",&n);
space = n-1;
for(i=1; i<=n;i++) {
for(j=1; j<=space; j++) {
printf(" ");
}
space--;
for(j=1; j<=2*i-1; j++) {
printf("*");
}
printf("\n");
}
space = 1;
for(i=1; i < n;i++) {
for(j=1; j<=space; j++) {
printf(" ");
}
space++;
for(j=1; j <=2*(n-i)-1; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Expected Output
* *** ***** *** *
Explanation of the Program
- The formula
2 * i - 1is standard for generating odd numbers (1, 3, 5, 7). This ensures the pyramid has a single star at the peak and grows symmetrically by 2 stars on each subsequent row. - To build the diamond, we literally just write the code for a right-side-up pyramid, and then immediately paste the code for an upside-down pyramid directly below it.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)