简体   繁体   中英

Printing Pascal Triangle in C

I've looked at some questions asked here regarding Pascal Triangle, yet I still can't seem to visualize how the algorithm would work.

[1]
[1 1]
[1 2 1]
[1 3 3 1] (3 comes from 1 + 2 on the previous row)
[1 4 6 4 1] (4 comes from 1 + 3, while 6 comes 3 + 3 on the previous row)
etc.

I have difficulties in imagining how adding the numbers visually in the triangle (just like how they told you to do it in school) can be implemented through loops. I would really appreciate a detailed answer in helping to bridge this.

do a 2-D array.

put 1 int he first cell, leave that row filled with garbabe

[1|g|g|g|...         // 1st row (arr[0][0] = 1;)

for the second row (and third, ...) start with 1 at the left, then add the value from the row above

[1|g|g|g|...        // 1st row
[1|g|g|g|...        // 2nd row (arr[1][0] = 1;)
                    //         (arr[1][1] = arr[1][0] + arr[0][0])

etc...

each cell has the value

cell[r][c] = cell[r-1][c-1] + cell[r-1]c]

for c>0. and

cell[r][0] = 1

just increase the range of c by one for each row, starting with 0 for first row, 1 for second...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM