Print a Mirrored Alphabet Pyramid in C
To print a mirrored alphabet pyramid in C, we need to structure the output such that the alphabet characters are aligned in a pyramid shape, with spaces preceding the letters to create a mirrored effect. This is achieved using nested loops—one for handling spaces and another for printing characters.
Examples to Print a Mirrored Alphabet Pyramid
1. Simple Mirrored Alphabet Pyramid
In this example, we print a mirrored alphabet pyramid where each row starts with spaces followed by consecutive alphabet characters starting from ‘A’.
main.c
</>
Copy
#include <stdio.h>
int main() {
int rows = 5; // Define the number of rows
for (int i = 1; i <= rows; i++) {
// Print leading spaces
for (int j = 1; j <= rows - i; j++) {
printf(" ");
}
// Print alphabet characters
for (char ch = 'A'; ch < 'A' + i; ch++) {
printf("%c", ch);
}
printf("\n");
}
return 0;
}
Explanation:
- We define the number of rows as
5
in the variablerows
. - The outer
for
loop runs from1
torows
, controlling the number of lines printed. - The first inner loop prints spaces to shift the letters to the right, creating a mirrored effect.
- The second inner loop prints alphabets starting from ‘A’ up to the required number of characters.
- Each row ends with a newline
\n
for formatting.
Output:
A
AB
ABC
ABCD
ABCDE
2. Mirrored Alphabet Pyramid in Reverse Order
In this example, we print a mirrored alphabet pyramid, but the letters appear in reverse order from the given row count.
main.c
</>
Copy
#include <stdio.h>
int main() {
int rows = 5; // Define the number of rows
for (int i = 1; i <= rows; i++) {
// Print leading spaces
for (int j = 1; j <= rows - i; j++) {
printf(" ");
}
// Print alphabet characters in reverse order
for (char ch = 'A' + i - 1; ch >= 'A'; ch--) {
printf("%c", ch);
}
printf("\n");
}
return 0;
}
Explanation:
- We define the number of rows using the variable
rows
and set it to5
. - The outer loop iterates from
1
torows
, creating the number of lines needed. - The first inner loop prints spaces to shift the pyramid towards the right.
- The second inner loop prints letters in reverse order, starting from a letter that depends on the current row index.
- Each iteration prints a new line using
\n
to separate pyramid rows.
Output:
A
BA
CBA
DCBA
EDCBA
Conclusion
In this tutorial, we explored different ways to print a mirrored alphabet pyramid in C:
- Basic Mirrored Alphabet Pyramid: We printed alphabets in increasing order with spaces for mirroring.
- Reverse Order Pyramid: We modified the logic to print letters in decreasing order.