C Program to Print an Alphabet Pyramid Pattern

1. Introduction

An alphabet pyramid pattern is an interesting way to practice C programming, especially for beginners looking to get a handle on loops and conditionals. This pattern involves printing letters of the alphabet in a pyramid shape, with each row containing the same letter which changes from 'A' onwards in each subsequent row. This tutorial will guide you through creating such a pattern in C.

2. Program Steps

1. Request the number of rows for the pyramid from the user.

2. Use nested loops: one to iterate through each row, and another to manage the printing of spaces and the alphabet for each row.

3. Increment the alphabet character used in each row.

3. Code Program

#include <stdio.h>

int main() {
    int rows, i, j, space;
    char ch = 'A';

    // Prompting user input for the number of rows
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    for(i = 1; i <= rows; i++) {
        // Printing leading spaces
        for(space = 1; space <= rows - i; space++) {
            printf(" ");
        }
        // Printing alphabet characters
        for(j = 1; j <= i; j++) {
            printf("%c ", ch);
        }
        ch++;
        printf("\n");
    }

    return 0;
}

Output:

Enter the number of rows: 5
    A
   B B
  C C C
 D D D D
E E E E E

Explanation:

1. The program starts with including the stdio.h library, essential for input and output operations.

2. main function initializes integer variables for loops (i, j, space) and a character variable ch starting from 'A'.

3. The user is prompted to enter the desired number of rows for the pyramid pattern.

4. A for loop iterates from 1 to the number of rows. Within this loop, another loop prints the required spaces to align the pyramid shape correctly.

5. Another inner loop prints the characters. In each row, the character ch is printed, followed by a space to separate the characters in the pyramid pattern. The character ch is incremented after completing each row to move to the next alphabet letter.

6. This process creates an alphabet pyramid, where each row contains the same letter, and each subsequent row uses the next letter in the alphabet sequence.

7. The program concludes with return 0;, signaling successful execution.


Comments