Pascal's triangle: Difference between revisions
Content added Content deleted
(Clojure) |
(added BASIC) |
||
Line 47: | Line 47: | ||
end Pascals_Triangle; |
end Pascals_Triangle; |
||
</ada> |
</ada> |
||
=={{header|BASIC}}== |
|||
===Summing from Previous Rows=== |
|||
{{works with|FreeBASIC}} |
|||
This implementation uses an array to store one row of the triangle. |
|||
DIM initializes the array values to zero. For first row, "1" is then stored in the array. |
|||
To calculate values for next row, the value in cell (i-1) is added to each cell (i). |
|||
This summing is done from right to left so that it can be done on-place, without using a tmp buffer. |
|||
Because of symmetry, the values can be displayed from left to right. |
|||
Space for max 5 digit numbers is reserved when formatting the display. |
|||
The maximum size of triangle is 100 rows, but in practice it is limited by screen space. |
|||
If the user enters value less than 1, the first row is still always displayed. |
|||
<freebasic>DIM i AS Integer |
|||
DIM row AS Integer |
|||
DIM nrows AS Integer |
|||
DIM values(100) AS Integer |
|||
INPUT "Number of rows: "; nrows |
|||
values(1) = 1 |
|||
PRINT TAB((nrows)*3);" 1" |
|||
FOR row = 2 TO nrows |
|||
PRINT TAB((nrows-row)*3+1); |
|||
FOR i = row TO 1 STEP -1 |
|||
values(i) = values(i) + values(i-1) |
|||
PRINT USING "##### "; values(i); |
|||
NEXT i |
|||
PRINT |
|||
NEXT row</freebasic> |
|||
===Using binary coefficients=== |
|||
{{works with|FreeBASIC}} |
|||
This implementation does not need an array to store values for each row, but the calculation is slightly more complex. |
|||
If the user enters value less than 1, nothing is displayed. |
|||
<freebasic>DIM c AS Integer |
|||
DIM i AS Integer |
|||
DIM row AS Integer |
|||
DIM nrows AS Integer |
|||
INPUT "Number of rows: "; nrows |
|||
FOR row = 0 TO nrows-1 |
|||
c = 1 |
|||
PRINT TAB((nrows-row)*3); |
|||
FOR i = 0 TO row |
|||
PRINT USING "##### "; c; |
|||
c = c * (row - i) / (i+1) |
|||
NEXT i |
|||
PRINT |
|||
NEXT row</freebasic> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |