Pascal's triangle: Difference between revisions

Line 89:
1 5 10 10 5 1</lang>
 
=={{header|BASICAPL}}==
===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.
 
Solution of Roberto Minervini
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.
 
{A←0,⍳⍵ ⋄ ⍉A∘.!A} 3
<lang freebasic>DIM i AS Integer
DIM row AS Integer
DIM nrows AS Integer
DIM values(100) AS Integer
 
1 0 0 0
INPUT "Number of rows: "; nrows
1 1 0 0
values(1) = 1
1 2 1 0
PRINT TAB((nrows)*3);" 1"
1 3 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</lang>
 
===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.
<lang 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</lang>
 
Note: Unlike most Basic implementations, FreeBASIC requires that all variables have been declared before use
(but this can be changed with compiler options).
 
=={{header|C}}==
Anonymous user