Write a c program to print number triangle.

Ram Pothuraju

 #include <stdio.h>


int main()

{

    int n, num = 1;


    // Read number of rows from user

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

    scanf("%d", &n);


    // Print number triangle

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

    {

        // Print spaces before numbers

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

        {

            printf(" ");

        }


        // Print numbers in ascending order

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

        {

            printf("%d ", num++);

        }


        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 numbers to center the triangle. We then print the numbers in ascending order up to the current row, and then 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. Also, note that the number sequence starts from 1 and increments by 1 for each new number.



Post a Comment

0Comments

Post a Comment (0)