1 //++++++++++++++++++++++++++
2 // PascalTri.cpp
3 //++++++++++++++++++++++++++
4
5 ///#include header
6 #include <iostream>
7 #include <fstream>
8 #include <iomanip> // setw(8)
9
10 ///Using & universal
11 using namespace std;
12
13 ///main(i)
14 int main()
15 {
16 ///declare
17 int n;
18 int i, j;
19 unsigned tri[51][51];
20
21 ///Prompt /Keyin
22 cout << " Please input size of Pascal triangle: ";
23 cin >> n;
24
25 ///within range
26 if (n<0 || n>=50) { cout <<"Only 0 ~ 50 !\n" << endl; return 1;}
27
28 ///tri[0][0] initial=1
29 tri[0][0] = 1;
30
31 ///from 1st layer to Nth layer
32 for (i = 1; i <= n; i++)
33 {
34 ///fill "1" in row_edge , col_edge
35 tri[i][0] = tri[0][i] = 1;
36
37 ///from 2nd layer to Nth layer
38 for (j = 1; j <= i-1; j++)//i=2 do 1st
39 {
40 ///layer sum
41 tri[i-j][j] = tri[i-j][j-1]+tri[i-j-1][j];
42 //i=2 j=1 1 1= 1 0 + 0 1
43 //i=3 j=1 2 1= 2 0 + 1 1
44 //i=3 j=2 1 2= 1 1 + 0 2
45
46 ///+
47 }//end for
48
49 ///+
50 }//end for
51
52 ///from zero layer to Nth layer
53 for (i = 0; i <= n; i++)
54 {
55 ///left_blank decrease
56 for (j = 0; j < (n-i) ; j++)
57 {
58 ///left_blank= setw(8)/2
59 cout << " " ;
60
61 ///+
62 }//end for
63
64 ///increase to layer end
65 for (j = 0; j <= i; j++)
66 {
67 ///Display setw(8)
68 cout << setw(8) << tri[i-j][j];
69
70 ///+
71 }//end for
72
73 ///CR/LF
74 cout << endl;
75
76 ///+
77 }//end for
78
79 ///main(o)
80 return 0 ;
81 } //main_end
82
This Blog is dedicated to Sir Johnson Lin
巴斯卡三角形 Pascal triangle
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言