Print a Hollow Alphabet Triangle Pattern in C
To print a hollow alphabet triangle pattern in C, we use nested loops to print characters in a triangular shape while ensuring that only the boundary characters and the base of the triangle are printed, leaving the inside of the triangle empty.
Examples of Hollow Alphabet Triangle Patterns
1. Basic Hollow Alphabet Triangle Pattern
In this example, we will print a hollow alphabet triangle where the first and last characters of each row are displayed, while the inside remains empty except for the last row, which is completely filled.
main.c
#include <stdio.h>
int main() {
int rows = 5;
char ch = 'A';
for (int i = 0; i < rows; i++) {
for (int j = 0; j <= i; j++) {
// Print character at the edges or the last row
if (j == 0 || j == i || i == rows - 1) {
printf("%c ", ch + j);
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Explanation:
- We declare an integer variable
rowsto define the height of the triangle and a character variablechinitialized to'A'. - The outer
forloop runs from0torows - 1, representing each row. - The inner
forloop runs from0toi, printing characters based on conditions. - The
ifcondition checks if the current position is at the start, end, or last row. If true, it prints the character; otherwise, it prints a space. - The character is calculated as
ch + jto display increasing letters in each row. - Each row ends with
printf("\n")to move to the next line.
Output:
A
A B
A C
A D
A B C D E
2. Hollow Inverted Alphabet Triangle
In this example, we will print a hollow inverted alphabet triangle where the first and last characters of each row are displayed, while the inside remains empty except for the first row, which is completely filled.
main.c
#include <stdio.h>
int main() {
int rows = 5;
char ch = 'A';
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows - i; j++) {
// Print character at the edges or the first row
if (j == 0 || j == rows - i - 1 || i == 0) {
printf("%c ", ch + j);
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Explanation:
- The variable
rowsdefines the height of the triangle, andchis initialized to'A'. - The outer
forloop runs from0torows - 1, controlling the number of rows. - The inner
forloop runs from0torows - i - 1, decreasing in size per row. - The
ifcondition checks if the position is at the start, end, or first row and prints the character accordingly. - The printed character is calculated as
ch + jfor increasing letters. - Each row is terminated using
printf("\n")to move to the next line.
Output:
A B C D E
A D
A C
A B
A
Conclusion
In this tutorial, we explored how to print hollow alphabet triangle patterns in C:
- Basic Hollow Alphabet Triangle: Displays an upright triangle with hollow spaces inside.
- Hollow Inverted Alphabet Triangle: Prints a downward-facing triangle with boundary characters.
By using nested loops and conditional statements, we can create different variations of hollow alphabet triangles in C.
