bolakecil
bolakecil

Reputation: 66

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.

Upvotes: 1

Views: 123

Answers (2)

pm100
pm100

Reputation: 50210

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 ...

Upvotes: 0

pmg
pmg

Reputation: 108986

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...

Upvotes: 1

Related Questions