Write a C program to print the Hollow Triangle Star Pattern using for loop, while loop, and functions with an example. The below program uses the nested for loops to iterate the rows and columns of a Triangle, and the if else condition checks and prints stars on the outer edges.
#include<stdio.h> int main(void) { int rows; printf("Enter Rows to Print Hollow Triangle = "); scanf("%d", &rows); for (int i = 1 ; i <= rows; i++ ) { for (int j = 1 ; j <= rows - i; j++ ) { printf(" "); } for (int k = 1 ; k <= i * 2 - 1; k++ ) { if ((i == 1 || i == rows) || (k == 1 || k == i * 2 - 1) ) printf("* "); else printf(" "); } printf("\n"); } }
C Program to Print Hollow Triangle Star Pattern
In this Hollow Triangle Star Pattern program, we replaced the for loop with the while loop.
#include<stdio.h> int main(void) { int rows; printf("Enter Rows to Print Hollow Triangle = "); scanf("%d", &rows); int i = 1 ; while (i <= rows ) { int j = 1 ; while ( j <= rows - i ) { printf(" "); j++; } int k = 1 ; while ( k <= i * 2 - 1 ) { if ((i == 1 || i == rows) || (k == 1 || k == i * 2 - 1) ) printf("* "); else printf(" "); k++; } printf("\n"); i++; } }
Output
Enter Rows to Print Hollow Triangle = 10
*
* *
* *
* *
* *
* *
* *
* *
* *
* * * * * * * * * * * * * * * * * * *
This example uses the do while loop and prints the Hollow Triangle Star pattern.
#include<stdio.h> int main(void) { int rows; printf("Enter Rows to Print Hollow Triangle = "); scanf("%d", &rows); int i = 1 ; do { int j = 0 ; do { printf(" "); j++; }while ( j <= rows - i ); int k = 1 ; do { if ((i == 1 || i == rows) || (k == 1 || k == i * 2 - 1) ) printf("* "); else printf(" "); k++; } while ( k <= i * 2 - 1 ); printf("\n"); i++; } while (i <= rows ); }
Output
Enter Rows to Print Hollow Triangle = 13
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* * * * * * * * * * * * * * * * * * * * * * * * *
In the below hollow Triangle pattern of stars program, the loopLogic function accepts the rows and characters to print the pattern using the symbol.
#include<stdio.h> void loopLogic(int rows, char ch) { for (int i = 1 ; i <= rows; i++ ) { for (int j = 1 ; j <= rows - i; j++ ) { printf(" "); } for (int k = 1 ; k <= i * 2 - 1; k++ ) { if ((i == 1 || i == rows) || (k == 1 || k == i * 2 - 1) ) printf("%c ", ch); else printf(" "); } printf("\n"); } } int main(void) { int rows; char ch; printf("Enter Character = "); scanf("%c", &ch); printf("Enter Rows to Print Hollow Triangle = "); scanf("%d", &rows); loopLogic(rows, ch); }
Output.
Enter Character = $
Enter Rows to Print Hollow Triangle = 15
$
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $