Write a C Program to print a hollow diamond star pattern using nested for loops, while loop, functions, and if-else statements. In this C hollow diamond example, the if statement checks for outer lines and prints stars otherwise, it prints empty spaces to get that hollow shape.
#include<stdio.h> int main(void) { int i, j, k, rows; printf("Enter Diamond Rows = "); scanf("%d", &rows); printf("Diamond Star Pattern\n"); for (i = 1 ; i <= rows; i++ ) { for (j = 1 ; j <= rows - i; j++ ) { printf(" "); } for (k = 1 ; k <= i * 2 - 1; k++ ) { if (k == 1 || k == i * 2 - 1) { printf("*"); } else { printf(" "); } } 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++ ) { if (k == 1 || k == i * 2 - 1) { printf("*"); } else { printf(" "); } } printf("\n"); } }
Output.
Enter Diamond Rows = 9
Diamond Star Pattern
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
In this C Hollow Diamond pattern program of stars, we replaced the for loop with a while loop.
#include<stdio.h> int main(void) { int i, j, k, rows; printf("Enter Diamond Rows = "); scanf("%d", &rows); i = 1 ; while (i <= rows) { j = 1 ; while (j <= rows - i) { printf(" "); j++; } k = 1 ; while ( k <= i * 2 - 1) { if (k == 1 || k == i * 2 - 1) { printf("*"); } else { printf(" "); } k++; } printf("\n"); i++ ; } i = rows - 1 ; while ( i > 0) { j = 1 ; while(j <= rows - i ) { printf(" "); j++; } k = 1 ; while (k <= i * 2 - 1 ) { if (k == 1 || k == i * 2 - 1) { printf("*"); } else { printf(" "); } k++; } printf("\n"); i-- ; } }
Enter Diamond Rows = 12
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
C Program to Print Hollow Diamond Star Pattern using do while loop
#include<stdio.h> int main(void) { int i, j, k, rows; printf("Enter Diamond Rows = "); scanf("%d", &rows); i = 1 ; do { j = 1 ; do { printf(" "); } while ( j++ <= rows - i) ; k = 1 ; do { if (k == 1 || k == i * 2 - 1) { printf("*"); } else { printf(" "); } } while ( ++k <= i * 2 - 1); printf("\n"); } while ( ++i <= rows) ; i = rows - 1 ; do { j = 1 ; do { printf(" "); } while(j++ <= rows - i ); k = 1 ; do { if (k == 1 || k == i * 2 - 1) { printf("*"); } else { printf(" "); } } while (++k <= i * 2 - 1 ); printf("\n"); } while ( --i > 0); }
Enter Diamond Rows = 7
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
In this C example, the result function prints the hollow diamond pattern of a given symbol.
#include<stdio.h> void result(int rows, int i, char ch) { for (int j = 1; j <= rows - i; j++) { printf(" "); } for (int k = 1; k <= i * 2 - 1; k++) { if (k == 1 || k == i * 2 - 1) { printf("%c", ch); } else { printf(" "); } } printf("\n"); } int main(void) { int i, rows; char ch; printf("Enter Symbol = "); scanf("%c", &ch); printf("Enter Diamond Rows = "); scanf("%d", &rows); for (i = 1; i <= rows; i++) { result(rows, i, ch); } for (i = rows - 1; i > 0; i--) { result(rows, i, ch); } }