Pascal triangle

Write a program to print the Pascal triangle.

Pascal Triangle:
    
        1
     1   1
   1    2  1
1  3    3   1

C Program
 
#include <stdio.h>
int main()
{
    int rows;
    int val;

    printf("Enter number of rows: ");
    scanf("%d", &rows);
    for (int i = 0i < rowsi++)
    {
        //print the spaces
        for (int space = 1space <= rows - ispace++)
        {
            printf("  ");
        }

        //print the values
        for (int j = 0j <= ij++)
        {
            //if first and last
            if (j == 0 || j == i)
            {
                val = 1;
            }
            else
            {
                val = val * (i - j + 1) / j;
            }

            printf("%4d "val);
        }
        printf("\n");
    }
    return 0;
}

Output:

Enter number of rows: 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1


No comments:

Post a Comment