Write a C program to print a Diamond number pattern using for loop, while loop, and functions with an example. In the below program, we used multiple nested for loops to iterate the rows and print the numbers in a diamond shape or pattern.
#include<stdio.h> int main(void) { int i, j, k, rows; printf("Enter Diamond Number Rows = "); scanf("%d", &rows); for(i = 1; i <= rows; i++) { for(j = 1; j <= rows - i; j++) { printf(" "); } for(k = 1; k <= i * 2 - 1; k++) { printf("%d", k); } printf("\n"); } for(i = rows - 1; i > 0; i--) { for(j = 1; j <= rows - i; j++) { printf(" "); } for(k = 1; k <= i * 2 - 1; k++) { printf("%d", k); } printf("\n"); } }
C Program to Print Diamond Number Pattern using for loop
It is another way of writing a program to display the diamond pattern of numbers using a for loop.
#include<stdio.h> void result(int rows, int i) { for (int j = 1 ; j <= rows - i; j++ ) { printf(" "); } for (int k = i ; k >= 1; k-- ) { printf("%d", k); } for (int l = 2 ; l <= i; l++) { printf("%d", l); } printf("\n"); } int main(void) { int i, rows; printf("Enter Diamond Number Rows = "); scanf("%d", &rows); for (i = 1 ; i <= rows; i++ ) { result(rows, i); } for (i = rows - 1 ; i > 0; i-- ) { result(rows, i); } }
Enter Diamond Number Rows = 9
1
212
32123
4321234
543212345
65432123456
7654321234567
876543212345678
98765432123456789
876543212345678
7654321234567
65432123456
543212345
4321234
32123
212
1
The below c program uses a while loop to print the diamond pattern of numbers using the above code.
#include<stdio.h> void result(int rows, int i) { int j = 1 ; while (j <= rows - i) { printf(" "); j++; } int k = i ; while (k >= 1 ) { printf("%d", k); k--; } int l = 2 ; while (l <= i) { printf("%d", l); l++; } printf("\n"); } int main(void) { int i, rows; printf("Enter Diamond Number Rows = "); scanf("%d", &rows); i = 1; while (i <= rows ) { result(rows, i); i++; } i = rows - 1 ; while ( i > 0 ) { result(rows, i); i--; } }
Enter Diamond Number Rows = 7
1
212
32123
4321234
543212345
65432123456
7654321234567
65432123456
543212345
4321234
32123
212
1