Index « Previous Next »

Question

The following set of numbers is popularly known as Pascal's Triangle.

pascal triangle

If we denote rows by i and column by j, then any element (except the boundary element) in the triangle is given by
Pi j = Pi - 1, j - 1 + Pi - 1, j
Write a program to calculate the elements of pascal triangle for 10 rows and print the results.

Source Code

#include <stdio.h>

int main()
{
    const int SIZE = 10;
    int previous[SIZE], current[SIZE], i, j, t;


    for (i = 0; i < SIZE; i++)
    {
        for (j = 0; j <= i; j++)
        {
            if (j == i || j == 0)
            {
                current[j] = 1;
            }
            else
            {
                current[j] = previous[j] + previous[j - 1];
            }
        }
        /* Print starting space of triangle */
        for (t = SIZE; t > i; t--)
        {
            printf(" ");
        }


        for (t = 0; t <= i; t++)
        {
            printf("%3d", current[t]);
            /* current array is copied to previous */
            previous[t] = current[t];
        }

        printf("\n");
    }
}