facebook like button

03 May, 2011

program 42: Pascal's triangle

The need:
     This program draws a pascal triangle upto certain numbers of rows. Pascal triangle is an arrangement of binomial coefficients for each row.

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int i,j,k[50],l[50][50],m;
    printf("Enter the number of rows.");
    scanf("%d",&m);
    for(i=1;i<=m;i++)
    {
        for(j=0;j<(m-i);j++)
        printf("   ");
        for(j=0;j<i;j++)
        {
            k[0]=1;
            if(j==i-1)
            k[j]=1;
            l[i][j]=k[j];
            k[j+1]=l[i-1][j]+l[i-1][j+1];
            printf("%5d ",k[j]);
        }
        printf("\n");
    }
}
-------------------------------------------- 

The approach: 
If you have already visited the wiki link given above in this post,you have come to know the logic that each number in the triangle is the sum of the two directly above it. This is the approach used here. To store the rows, a double array of integers has been used and the current row(the row that is being printed) is evaluated and temporarily stored in array k which is also added to double array 'l' each time for next row calculation.


Remarks:

1. We can avoid using two dimensional array in place of that we can use a one dimensional array. Here I used 2 dimensional because at that time I made this program in this way. One advantage of using 2 dimensional array is that now we have the whole pascal stored in that.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply