Print a Diamond Number Pattern in C
To print a diamond number pattern in C, we use nested loops. The outer loop controls the number of rows, while the inner loops manage spaces and numbers to form the diamond shape.
The Diamond Number pattern consists of an upper half (pyramid) and a lower half (inverted pyramid). In this tutorial, we will implement different versions of the diamond pattern using loops.
Examples of Diamond Number Pattern
1. Simple Diamond Number Pattern
In this example, we print a simple diamond number pattern where numbers increase from the top to the middle row and then decrease symmetrically.
main.c
</>
Copy
#include <stdio.h>
int main() {
int n = 5; // Number of rows in the upper half
// Upper half of the diamond
for (int i = 1; i <= n; i++) {
for (int j = i; j < n; j++) {
printf(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
printf("%d", j);
}
printf("\n");
}
// Lower half of the diamond
for (int i = n - 1; i >= 1; i--) {
for (int j = n; j > i; j--) {
printf(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
printf("%d", j);
}
printf("\n");
}
return 0;
}
Explanation:
- We declare
n
as the number of rows in the upper half. - The first
for
loop prints the upper half of the diamond:- First, we print spaces using an inner loop (
j
goes fromi
ton
). - Next, we print numbers from
1
to(2 * i - 1)
.
- First, we print spaces using an inner loop (
- The second
for
loop prints the lower half:- Spaces are printed similarly but in reverse order.
- Numbers decrease in a symmetric pattern.
Output:
1
123
12345
1234567
123456789
1234567
12345
123
1
2. Diamond Number Pattern with Centered Digits
In this example, we create a diamond number pattern where each row contains the same number as the row index.
main.c
</>
Copy
#include <stdio.h>
int main() {
int n = 5;
// Upper half
for (int i = 1; i <= n; i++) {
for (int j = i; j < n; j++) {
printf(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
printf("%d", i);
}
printf("\n");
}
// Lower half
for (int i = n - 1; i >= 1; i--) {
for (int j = n; j > i; j--) {
printf(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
printf("%d", i);
}
printf("\n");
}
return 0;
}
Explanation:
- We declare
n
as the number of rows. - In the first loop, we print the upper half:
- Spaces decrease as the row index increases.
- The row index is printed
(2 * i - 1)
times.
- In the second loop, the lower half mirrors the upper half.
Output:
1
222
33333
4444444
555555555
4444444
33333
222
1
Conclusion
In this tutorial, we learned how to print diamond number patterns in C:
- We implemented a simple diamond number pattern.
- We created a pattern where the row number is repeated.
- We used nested loops to print spaces and numbers symmetrically.