1

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.

bolakecil
  • 66
  • 1
  • 7

2 Answers2

1

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

pmg
  • 106,608
  • 13
  • 126
  • 198
  • won't this actually make `arr[1][1]` = `2` due to `arr[1][0]` equals to `1` + `arr[0][0]` equals to `1` when `arr[1][1]` is actually supposed to be `1`? – bolakecil Mar 13 '22 at 23:48
  • 1
    Update: Nevermind, my bad. It works! Thank you for the brief yet helpful answer :) – bolakecil Mar 13 '22 at 23:57
0

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

pm100
  • 48,078
  • 23
  • 82
  • 145