Write a c program to print alphabet triangle.

Ram Pothuraju

 #include <stdio.h>


int main()

{

    int n;


    // Read number of rows from user

    printf("Enter the number of rows: ");

    scanf("%d", &n);


    // Print alphabet triangle

    for (int i = 0; i < n; i++)

    {

        // Print spaces before letters

        for (int j = 0; j < n - i - 1; j++)

        {

            printf(" ");

        }


        // Print letters in ascending order

        for (int j = 0; j <= i; j++)

        {

            printf("%c ", 'A' + j);

        }


        // Print letters in descending order

        for (int j = i - 1; j >= 0; j--)

        {

            printf("%c ", 'A' + j);

        }


        printf("\n");

    }


    return 0;

}



In this program, we first read the number of rows for the triangle from the user using the scanf() function.

We then use nested loops to print each row of the triangle. For each row, we first print the necessary spaces before the letters to center the triangle. We then print the letters in ascending order up to the current row, and then in descending order from the second-last letter down to 'A'. Finally, we move to the next line using the printf() function.

Note that this program assumes that the number of rows entered by the user is positive. You may want to add input validation to ensure that the input is valid.

Post a Comment

0Comments

Post a Comment (0)