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:

  1. We define the number of rows as 5 in the variable rows.
  2. The outer for loop runs from 1 to rows, controlling the number of lines printed.
  3. The first inner loop prints spaces to shift the letters to the right, creating a mirrored effect.
  4. The second inner loop prints alphabets starting from ‘A’ up to the required number of characters.
  5. 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:

  1. We define the number of rows using the variable rows and set it to 5.
  2. The outer loop iterates from 1 to rows, creating the number of lines needed.
  3. The first inner loop prints spaces to shift the pyramid towards the right.
  4. The second inner loop prints letters in reverse order, starting from a letter that depends on the current row index.
  5. 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:

  1. Basic Mirrored Alphabet Pyramid: We printed alphabets in increasing order with spaces for mirroring.
  2. Reverse Order Pyramid: We modified the logic to print letters in decreasing order.