Thứ Hai, 1 tháng 9, 2014

Printing pascal triangle in c.

Here  is a pattern of pascal triangle..






It looks tough to code by seeing above pattern ,but it follows a specific logic called triangular array of the binomial coefficients..

lets see how it looks ..

Now its looking easy to code..we have to give spaces and calculate binomial coefficients using factorial method.

Solution :
-----------------------
#include<stdio.h>
#include<conio.h>
int factorial(int);
int main()
{
    int length,space,index,res,printvalue;
    printf("Enetr th length of your triangle");
    scanf("%d",&length);
    for(index=0;index<length;index++)
    {
    //give spaces first
        for(space=0;space<=(length-index-1);space++)
           printf(" ");
    //print fact value
        for(printvalue=0;printvalue<=index;printvalue++)
        {
            res=factorial(index)/(factorial(index-printvalue)*factorial(printvalue));
            printf("%d ",res);
        }
    //move to next line
        printf("\n");
    }

return 0;
}
int factorial(int num)
{
    int fact=1,index;
    for(index=1;index<=num;index++)
    fact=fact*index;
    return fact;

}

output:
---------------------------------
    
                  

Không có nhận xét nào:

Đăng nhận xét