Diamond Pattern (Star Pattern)
This pattern is a combination of pyramid + inverted pyramid and is very important for exams.
Diamond Pattern Shape
*
***
*****
*******
*****
***
*Key Logic (Very Important)
A diamond has two parts:
- Upper pyramid
- Lower inverted pyramid
Both parts use:
- Spaces
- Stars
1. Diamond Pattern Program (C)
c
1
2#include <stdio.h>
3
4int main() {
5 int i, j, k;
6 int n = 4; // half height
7
8 // Upper pyramid
9 for (i = 1; i <= n; i++) {
10 for (j = 1; j <= n - i; j++) {
11 printf(" ");
12 }
13 for (k = 1; k <= 2*i - 1; k++) {
14 printf("*");
15 }
16 printf("\n");
17 }
18
19 // Lower inverted pyramid
20 for (i = n - 1; i >= 1; i--) {
21 for (j = 1; j <= n - i; j++) {
22 printf(" ");
23 }
24 for (k = 1; k <= 2*i - 1; k++) {
25 printf("*");
26 }
27 printf("\n");
28 }
29
30 return 0;
31}How the Logic Works
ncontrols the size- First loop builds the top
- Second loop builds the bottom
- Middle row appears only once
Visual Thinking (Tip)
- Count rows:
2n - 1 - Middle row = maximum stars
- Stars increase then decrease
