How to display a pascal triangle using a 2D array in C++?

Guys how can i display a pascal triangle in forloop?

Here's my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>

using namespace std;

void print(int a[3][3])
 { 
  for(int r=0; r<3; r++)
	 { cout<<endl;
	  for(int c=0; c<3;c++)
           {// how to display a pascal triangle?    
	     cout<<a[r][c]<<" ";
	   }	 
	 }
	 
 }

int main()
{
  int a[3][3];
  int x,y;
  
  for(x=0; x<3; x++)
   {
    for(y=0; y<3; y++)
	{
		cout<<"Please Enter a number : ";
		cin>>a[x][y];
	}
   }
   print(a);
}


this should be the output:

1
2
3
 123
  56  
   9

Last edited on
OP wrote:
123
  56  
   9

Are you sure that's Pascal's triangle ?
Look here : http://en.wikipedia.org/wiki/Pascal's_triangle
Example of Pascal's triangle :

   1
  1 1
 1 2 1
1 3 3 1

Although it could be very easy to generate one,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int base_width;
    cin >> base_width;
    std::vector<int> last_row(base_width,0);
    std::vector<int> curr_row(base_width,0);
    for(int i = 0 ; i < base_width ; ++i)
    {
        curr_row[0] = 1;
        for(int j = i-1 ; j > 0 ; --j)
        {
            curr_row[j] = last_row[j-1] + last_row[j];
        }
        curr_row[i] = 1;
        for(int j = 0 ; j <= i ; ++j)
            cout << curr_row[j] << " ";
        last_row = {curr_row.begin(),curr_row.end()};
        cout << endl;
    }
    return 0;
}
Last edited on
Topic archived. No new replies allowed.