cloopspascals-triangle

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.


Solution

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