Pascal Triangle Challenge Posted on May 29th
A simple challenge for c/c++ fans, use only 2 variable and 2 for loop to print a pascal triangle looks as bellow
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
My solution:
Trackback URL
Here’s mine :-)
void piramid(int const c)
{
int r, x;
/* c: center of pyramid, r: row/height of pyramid */
for (r = c; r > 0; r--)
{
/* int start = r; */
/* int end = (2 * c - r); */
/* start: start printing numbers, end: stop printing numbers */
for (x = 1; x < = (2 * c - r); x++)
Commented toydi on May 30th, 2007.{
if (x < r) printf(" ");
else if (x <= c) printf("%d", x - r + 1);
else printf("%d", (2 * c - r) - x + 1);
}
printf("\n");
}
}
toydi: Its too bad that the comment here got word count limit, why don’t you post on your blog instead?
Commented mysurface on May 30th, 2007.the programing techniq is very nice.thanq for helping
Commented i.siva reddy on August 21st, 2007.That’s not Pascal’s triangle, which contains the coefficients of the
binomial raised to some given power.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
etc.
And you need only one variable, outside the for look counters, of course.
Based on the fact that each number is n choose k, with n the row number and k
the position in the row.
So it becomes:
for (unsigned n = 0; n
Commented dzeta on August 29th, 2007.Truncated code:
for (unsigned n = 0; n
Commented dzeta on August 29th, 2007.i want a simple program n its too mch complicated
Commented nishidh on October 23rd, 2007.check this college level implementation. Hope this is easy to digest.
#include
#include
main()
{
int level_count = 0, space_count, i, j;
printf(”\n Please enter the number of levels for triangle: “);
Commented Subash on July 24th, 2008.scanf(”%d”, &level_count);
printf(”\n Here goes your pascal triangle \n”);
space_count = level_count;
for (i = 0; i < level_count; i++)
{
for (j = 0; j < space_count; j++)
{
putchar(’ ‘);
}
space_count–;
for (j = 1; j = 1; j–)
{
printf(”%d”,j);
}
printf(”\n”);
}
}
that works for applying the spaces, it doesnt answer any questions about the actual calculation of the rows though. you will get a line of 1s decending but how would you go about adding the numbers in the previous row to create the next.
Commented adam on August 12th, 2008.