The following code snippet prints the Pascals triangle,I have got this snippet from the internet but I am unable to get the formula for bin.If anyone can help me out with it I would be thankfull\
#include<stdio.h>
int main()
{
int bin=1,p,q=0,r,x;
clrscr();
printf("Rows you want to input:");
scanf("%d",&r);
printf("\nPascal's Triangle:\n");
while(q<开发者_C百科r)
{
printf("ROW %d",q);
for(p=40-3*q;p>0;--p)
printf(" ");
for(x=0;x<=q;++x)
{
if((x==0)||(q==0))
bin=1;
else
bin=(bin*(q-x+1))/x;
printf("%6d",bin);
}
printf("\n");
++q;
}
getchar();
return 0;
}
Ok, let's take a look. The actuall formula is the inner for loop:
for(x=0;x<=q;++x)
{
if((x==0)||(q==0))
bin=1;
else
bin=(bin*(q-x+1))/x;
printf("%6d",bin);
}
q represents the row of the pascal triangle, starting at the top.
x represents the element number in the row. Since in row 1 there will be 1 element in row 2 two elemnts.
So the for(x=0;x<=q;++x)
makes sense.
now to the if clause if((x==0)||(q==0))
. If x is 0 than we are at the left side of the triangle or beginning of the triangle row, which is always 1. If q is 0 than obviosly this is the first row of the triangle (starting at the top) which is also always 1. Since there is the only one element.
now to the else clause, which is probably the most interesting part:
else
bin=(bin*(q-x+1))/x;
The first time we get in to this clause is after q was 0 and x was 0 at the start of the loop and was set to 1. This is important since bin was defined outside of the for loop and keeps the value from iteration to iteration. So now x is 2 and bin is 1. Again q represents the row number and the length of the row. To understand this you should look at the wikipedia page of the pascal's triangle. Especially the part with
Calculating an individual row or diagonal by itself
there you will find the formula written down again. The important word here are factorials. Also looking at the article about the pascal matrix might be helpful.
I'll try to explain it but (i hate when somebody says that) you have to see it. Take a look of the diagonals of the pascal triangle and at the inner part of the formula (q-x+1)
. Now compute the values which you will alsways get for every diagonal. You see a pattern? I hope now things start to make sense.
Print the values that are used to calculate bin in the loop to understand how it works
/* ... */
else
{
printf("new bin=(%d*(%d-%d*1))/%d\n", bin, q, x, x);
bin=(bin*(q-x*1))/x;
}
精彩评论