Can anyone tell how to print a pascal's triangle...
i've wriiten a code but it is not printing the triangle as the way iwanted it to..
here is my code:

#include<stdio.h>
#include<conio.h>
void main()
{
int n,a[50][50],x,y;
clrscr();
printf("Enter the number rows:\t");
scanf("%d",&n);
for(x=0;x<n;x++)
{
for(y=0;y<=x;y++)
{
if((y==x)||(y==0))
{
a[x][y] = 1;
}
else
{
a[x][y] = a[x-1][y-1]+a[x-1][y];
}
printf("%4d",a[x][y]);
}
printf("\n\n");
}
getch();
}

My output is:
Enter the number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

But i want the output as:
------------------- 1
----------------- 1 1
----------------- 1 2 1
---------------- 1 3 3 1

can anyone help me.....????

thanks

This looks like C and not C++...

Use C++ implementations--

#include <iostream>

using namespace std;

int main(){

     cout << " Testing 123... " << endl;
     cin.get();
     return 0;
}

Use code tags and things will space out nicely. Spacing is retained when you use code tags:

[code]

// paste formatted code or output here

[/code]

1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

Keep in mind that this is going to go into double digits soon, so keep that in mind when spacing. You may want to reserve 3 or 4 spaces for each number to account for double digits. I'd use 4 because it is divisible by 2 and thus will make things line up more nicely. You'll want to pad single digit numbers with an extra space so things line up. Here is what you'll want to do. You need to, before displaying anything, calculate how many characters the BOTTOM of the tree. Say you use 4 characters per number and your tree is 7 rows deep. Thus the bottom row has 7 numbers. The top row has 1 number, which is located above the 4th number of the bottom row, so you need to "pad" the top row by 3 numbers, each of which take 4 spaces. 3 x 4 so you need to pad the top row with 12 spaces, then row 2 by 10 spaces, row 3 by 8 spaces, etc. Each row below starts 2 spaces below the row above. You "pad" by displaying a space using cout.

The display above uses 2 spaces per number rather than 4, but if you have double digit numbers, bump it up to 4 spaces per number. I chose 4 rather than 3 because it's divisible by 2, so you get a less lop-sided looking tree.

This article has been dead for over six months. Start a new discussion instead.