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:

#include<stdio.h> #include<stdlib.h> void piramid(int const c) { int x,y; for(y=0; y<c; y++) { for(x=0; x<c-(1+y)+((y*2)+1); x++) { if(x<(c-(y+1)))printf(" "); else { if(x-(c-(y+2))>y+1) printf("%d",(2*y)+2-(x-(c-(y+2)) )); else printf("%d",(x-(c-(y+1))+1 )); } } printf("\n"); } } int main(int argc, char* argv[]) { if (argc==2) { if (atoi(argv[1])>9 || atoi(argv[1])<=1) { printf("Insert range within 2 to 9, ig. %s 9\n",argv[0]); return 1; } piramid(atoi(argv[1])); } else printf("Insert range within 2 to 9, ig. %s 9\n",argv[0]); return 0; }

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++) { 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?

the programing techniq is very nice.thanq for helping

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

Truncated code:

for (unsigned n = 0; n

i want a simple program n its too mch complicated

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: “);

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.