Pascal's triangle: Difference between revisions

m
→‎{{header|Wren}}: Minor tidy and now uses binomial method in Math module.
m (→‎{{header|Wren}}: Minor tidy and now uses binomial method in Math module.)
 
(145 intermediate revisions by 58 users not shown)
Line 1:
{{task|Arithmetic operations}}
 
[[wp:Pascal's triangle|Pascal's triangle]]   is an arithmetic and geometric figure firstoften imaginedassociated bywith  the name of [[wp:Blaise Pascal|Blaise Pascal]]., but also studied centuries earlier in India, Persia, China and elsewhere.
 
Its first few rows look like this: <b>
1
1 1
1 2 1
1 3 3 1 </b>
where each element of each row is either 1 or the sum of the two elements right above it.
 
Line 17:
::: &nbsp; '''1''' &nbsp; (since the last element of each row doesn't have two elements above it)
 
So the triangle now looks like this: <b>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1 </b>
 
Each row &nbsp; <tt> n </tt> &nbsp; (starting with row &nbsp; 0 &nbsp; at the top) shows the coefficients of the binomial expansion of &nbsp; <big><big> (x + y)<sup>n</sup>. </big></big>
Line 38:
* [[Evaluate binomial coefficients]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F pascal(n)
V row = [1]
V k = [0]
L 0 .< max(n, 0)
print(row.join(‘ ’).center(16))
row = zip(row [+] k, k [+] row).map((l, r) -> l + r)
 
pascal(7)</syntaxhighlight>
 
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
</pre>
 
=={{header|360 Assembly}}==
{{trans|PL/I}}
<langsyntaxhighlight lang="360asm">* Pascal's triangle 25/10/2015
PASCAL CSECT
USING PASCAL,R15 set base register
Line 78 ⟶ 101:
XD DS CL12 temp
YREGS
END PASCAL</langsyntaxhighlight>
{{out}}
<pre>
Line 96 ⟶ 119:
=={{header|8th}}==
One way, using array operations:
<langsyntaxhighlight lang="forth">
\ print the array
: .arr \ a -- a
Line 112 ⟶ 135:
\ print the first 16 rows:
[1] ' pasc 16 times
</syntaxhighlight>
</lang>
 
Another way, using the relation between element 'n' and element 'n-1' in a row:
<langsyntaxhighlight lang="forth">
: ratio \ m n -- num denom
tuck n:- n:1+ swap ;
Line 137 ⟶ 160:
 
15 pasc
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
BYTE count=[10],row,item
CHAR ARRAY s(5)
INT v
 
FOR row=0 TO count-1
DO
v=1
FOR item=0 TO row
DO
StrI(v,s)
Position(2*(count-row)+4*item-s(0),row+1)
Print(s)
v=v*(row-item)/(item+1)
OD
PutE()
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pascal's_triangle.png Screenshot from Atari 8-bit computer]
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
</pre>
 
=={{header|Ada}}==
Line 143 ⟶ 200:
The specification of auxiliary package "Pascal". "First_Row" outputs a row with a single "1", "Next_Row" computes the next row from a given row, and "Length" gives the number of entries in a row. The package is also used for the Catalan numbers solution [[http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle]]
 
<langsyntaxhighlight lang="ada">package Pascal is
type Row is array (Natural range <>) of Natural;
Line 153 ⟶ 210:
function Next_Row(R: Row) return Row;
end Pascal;</langsyntaxhighlight>
 
The implementation of that auxiliary package "Pascal":
 
<langsyntaxhighlight Adalang="ada">package body Pascal is
function First_Row(Max_Length: Positive) return Row is
Line 182 ⟶ 239:
end Length;
end Pascal;</langsyntaxhighlight>
 
The main program, using "Pascal". It prints the desired number of rows. The number is read from the command line.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line, Pascal; use Pascal;
 
procedure Triangle is
Line 203 ⟶ 260:
Row := Next_Row(Row);
end loop;
end Triangle;</langsyntaxhighlight>
 
{{out}}
Line 222 ⟶ 279:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">PRIO MINLWB = 8, MAXUPB = 8;
OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b),
MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b);
Line 240 ⟶ 297:
# WHILE # i < stop DO
row := row[AT 1] + row[AT 2]
OD</langsyntaxhighlight>
{{Out}}
<pre>
Line 252 ⟶ 309:
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% prints the first n lines of Pascal's triangle lines %
% if n is <= 0, no output is produced %
procedure printPascalTriangle( integer value n ) ;
if n > 0 then begin
integer array pascalLine ( 1 :: n );
pascalLine( 1 ) := 1;
for line := 1 until n do begin
for i := line - 1 step - 1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i );
pascalLine( line ) := 1;
write( s_w := 0, " " );
for i := line until n do writeon( s_w := 0, " " );
for i := 1 until line do writeon( i_w := 6, s_w := 0, pascalLine( i ) )
end for_line ;
end printPascalTriangle ;
 
printPascalTriangle( 8 )
 
end.</syntaxhighlight>
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="Amazing Hopper">
#include <jambo.h>
#define Mulbyandmoveto(_X_) Mul by '_X_', Move to '_X_'
 
Main
filas=0, Get arg numeric '2', Move to 'filas'
i=0, r=""
Loop if( var 'i' Is less than 'filas' )
c=1, j=0
Set 'c' To str, Move to 'r'
Loop if ( var 'j' Is less than 'i' )
Set 'i' Minus 'j', Plus one 'j', Div it; Mul by and move to 'c'
Multi cat ' r, "\t", Str(c) '; Move to 'r'
++j
Back
Printnl 'r'
++i
Back
End
</syntaxhighlight>
{{out}}
<pre>
$ hopper jm/pascal.jambo 14
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
 
</pre>
 
=={{header|APL}}==
Pascal' s triangle of order ⍵
=== Dyalog APL ===
<syntaxhighlight lang="apl">
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}
</syntaxhighlight>
 
example
 
<syntaxhighlight lang="apl">
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}5
</syntaxhighlight>
 
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
</pre>
=== GNU APL ===
GNU APL doesn't allow multiple statements within lambdas so the solution is phrased differently:
 
<langsyntaxhighlight lang="apl">
{A←0{⍉⍵∘.!⍵} 0,⍳⍵ ⋄ ⍉A∘.!A}
</syntaxhighlight>
</lang>
 
example
 
<langsyntaxhighlight lang="apl">
{A←0{⍉⍵∘.!⍵} 0,⍳⍵ ⋄ ⍉A∘.!A} 3
</syntaxhighlight>
</lang>
 
<pre>
Line 273 ⟶ 424:
1 3 3 1
</pre>
 
 
=={{header|AppleScript}}==
Drawing n rows from a generator:
<syntaxhighlight lang="applescript">-------------------- PASCAL'S TRIANGLE -------------------
 
<lang AppleScript>-- pascal :: Int ->Generator [[Int]]
on pascal(intRows)
script nextRow
on |λ|(row)
script addRow
on nextRow zipWith(my plus, {0} & row, row & {0})
end script add|λ|
on lambda(a, b)
a + b
end lambda
end script
zipWith(add, [0] & row, row & [0])
end nextRow
on lambda(xs)
xs & {nextRow(item -1 of xs)}
end lambda
end script
iterate(nextRow, {1})
foldr(addRow, {{1}}, range(1, intRows - 1))
end pascal
 
 
--------------------------- TEST -------------------------
-- TEST
 
on run
set lstTriangle toshowPascal(take(7, pascal(7)))
script spaced
on lambda(xs)
script rightAlign
on lambda(x)
text -4 thru -1 of (" " & x)
end lambda
end script
intercalate("", map(rightAlign, xs))
end lambda
end script
script indented
on lambda(a, x)
set strIndent to leftSpace of a
{rows:strIndent & x & linefeed & rows of a, leftSpace:leftSpace of a & " "}
end lambda
end script
rows of foldr(indented, {rows:"", leftSpace:""}, map(spaced, lstTriangle))
end run
 
 
------------------------ FORMATTING ----------------------
 
-- showPascal :: [[Int]] -> String
-- GENERIC LIBRARY FUNCTIONS
on showPascal(xs)
set w to length of intercalate(" ", item -1 of xs)
script align
on |λ|(x)
|center|(w, space, intercalate(" ", x))
end |λ|
end script
unlines(map(align, xs))
end showPascal
 
 
------------------------- GENERIC ------------------------
 
-- center :: Int -> Char -> String -> String
on |center|(n, cFiller, strText)
set lngFill to n - (length of strText)
if lngFill > 0 then
set strPad to replicate(lngFill div 2, cFiller) as text
set strCenter to strPad & strText & strPad
if lngFill mod 2 > 0 then
cFiller & strCenter
else
strCenter
end if
else
strText
end if
end |center|
 
 
-- intercalate :: String -> [String] -> String
on intercalate(sep, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, sep}
set s to xs as text
set my text item delimiters to dlm
return s
end intercalate
 
 
-- iterate :: (a -> a) -> a -> Generator [a]
on iterate(f, x)
script
property v : missing value
property g : mReturn(f)'s |λ|
on |λ|()
if missing value is v then
set v to x
else
set v to g(v)
end if
return v
end |λ|
end script
end iterate
 
 
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
2 ^ 30 -- (simple proxy for non-finite)
end if
end |length|
 
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to lambda(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
 
-- map :: (a -> b) -> [a] -> [b]
Line 350 ⟶ 523:
set lst to {}
repeat with i from 1 to lng
set end of lst to lambda|λ|(item i of xs, i, xs)
end repeat
return lst
Line 356 ⟶ 529:
end map
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
-- min :: Ord a => a -> a -> a
on zipWith(f, xs, ys)
on min(x, y)
set nx to length of xs
setif nyy to< lengthx of ysthen
if nx < 1 or ny < 1 theny
{}
else
x
set lng to cond(nx < ny, nx, ny)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to lambda(item i of xs, item i of ys)
end repeat
return lst
end tell
end if
end zipWithmin
 
 
-- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b)
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on cond(bool, f, g)
on mReturn(f)
if bool then
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
gscript
property |λ| : f
end script
end if
end condmReturn
 
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
 
 
-- range :: Int -> Int -> [Int]
-- plus :: Num -> Num -> Num
on range(m, n)
on plus(a, b)
set lng to (n - m) + 1
seta base+ to m - 1b
end plus
set lst to {}
 
repeat with i from 1 to lng
 
set end of lst to i + base
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return lstout & dbl
end rangereplicate
 
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturntake :: HandlerInt -> Script[a] -> [a]
-- take :: Int -> String -> String
on mReturn(f)
on take(n, xs)
if class of f is script then
set c to class fof xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set end of ys to xs's |λ|()
end repeat
return ys
else
scriptmissing value
property lambda : f
end script
end if
end mReturn</lang>take
 
 
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
 
 
-- unwords :: [String] -> String
on unwords(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, space}
set s to xs as text
set my text item delimiters to dlm
return s
end unwords
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys))
if 1 > lng then return {}
set xs_ to take(lng, xs) -- Allow for non-finite
set ys_ to take(lng, ys) -- generators like cycle etc
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith</syntaxhighlight>
{{Out}}
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1</pre>
 
</pre>
=={{header|Arturo}}==
{{trans|Nim}}
<syntaxhighlight lang="rebol">pascalTriangle: function [n][
triangle: new [[1]]
 
loop 1..dec n 'x [
'triangle ++ @[map couple (last triangle)++[0] [0]++(last triangle) 'x -> x\[0] + x\[1]]
]
 
return triangle
]
 
loop pascalTriangle 10 'row [
print pad.center join.with: " " map to [:string] row 'x -> pad.center x 5 60
]</syntaxhighlight>
 
{{out}}
 
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1</pre>
 
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?p=276617#276617 discussion]
<langsyntaxhighlight AutoHotkeylang="autohotkey">n := 8, p0 := "1" ; 1+n rows of Pascal's triangle
Loop %n% {
p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1
Line 447 ⟶ 701:
 
GuiClose:
ExitApp</langsyntaxhighlight>
 
Alternate {{works with|AutoHotkey L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">Msgbox % format(pascalstriangle())
Return
 
Line 474 ⟶ 728:
: p[row-1, col])
Return p
}</langsyntaxhighlight>
n <= 0 returns empty
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">$ awk 'BEGIN{for(i=0;i<6;i++){c=1;r=c;for(j=0;j<i;j++){c*=(i-j)/(j+1);r=r" "c};print r}}'</langsyntaxhighlight>
{{Out}}<pre>
1
Line 487 ⟶ 741:
1 5 10 10 5 1
</pre>
 
 
=={{header|Bait}}==
<syntaxhighlight lang="bait">
// Create a Pascal's triangle with a given number of rows.
// Returns an empty array for row_nr <= 0.
fun pascals_triangle(row_nr i32) [][]i32 {
mut rows := [][]i32
 
// Iterate over all rows
for r := 0; r < row_nr; r += 1 {
// Store the row above the current one
mut above := rows[r - 1]
 
// Fill the current row. It contains r + 1 numbers
for i := 0; i <= r; i += 1 {
// First number is always 1
if i == 0 {
rows.push([1]) // Push new row
}
// Last number is always 1
else if i == r {
rows[r].push(1)
}
// Other numbers are the sum of the two numbers above them
else {
rows[r].push(above[i - 1] + above[i])
}
}
}
 
return rows
}
 
 
// Helper function to pretty print triangles.
// It still get's ugly once numbers have >= 2 digits.
fun print_triangle(triangle [][]i32) {
for i, row in triangle {
// Create string with leading spaces
mut s := ' '.repeat(triangle.length - i - 1)
 
// Add each number to the string
for n in row {
s += n.str() + ' '
}
 
// Print and trim the extra trailing space
println(s.trim_right(' '))
}
}
 
 
fun main() {
print_triangle(pascals_triangle(7))
}
</syntaxhighlight>
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
</pre>
 
 
=={{header|BASIC}}==
Line 501 ⟶ 823:
If the user enters value less than 1, the first row is still always displayed.
 
<langsyntaxhighlight lang="freebasic">DIM i AS Integer
DIM row AS Integer
DIM nrows AS Integer
Line 516 ⟶ 838:
NEXT i
PRINT
NEXT row</langsyntaxhighlight>
 
=={{header|Batch File}}==
Based from the Fortran Code.
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 558 ⟶ 880:
for /l %%A in (1,1,%numspaces%) do set "space=!space! "
goto :EOF
::/The Functions.</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 579 ⟶ 901:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> nrows% = 10
colwidth% = 4
Line 591 ⟶ 913:
NEXT
PRINT
NEXT row%</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 603 ⟶ 925:
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let pascal(n) be
for i=0 to n-1
$( let c = 1
for j=1 to 2*(n-1-i) do wrch(' ')
for k=0 to i
$( writef("%I3 ",c)
c := c*(i-k)/(k+1)
$)
wrch('*N')
$)
let start() be pascal(8)</syntaxhighlight>
{{out}}
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1</pre>
 
=={{header|Befunge}}==
<langsyntaxhighlight Befungelang="befunge">0" :swor fo rebmuN">:#,_&> 55+, v
v01*p00-1:g00.:<1p011p00:\-1_v#:<
>g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@</langsyntaxhighlight>
{{Out}}
<pre>Number of rows: 10
Line 621 ⟶ 968:
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1 </pre>
 
=={{header|BQN}}==
 
Displays n rows.
 
<syntaxhighlight lang="bqn">Pascal ← {(0⊸∾+∾⟜0)⍟(↕𝕩)⋈1}
 
•Show¨Pascal 6</syntaxhighlight>
<syntaxhighlight lang="text">⟨ 1 ⟩
⟨ 1 1 ⟩
⟨ 1 2 1 ⟩
⟨ 1 3 3 1 ⟩
⟨ 1 4 6 4 1 ⟩
⟨ 1 5 10 10 5 1 ⟩</syntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( out$"Number of rows? "
& get':?R
& -1:?I
Line 640 ⟶ 1,001:
)
&
)</langsyntaxhighlight>
{{Out}}
<pre>Number of rows?
Line 654 ⟶ 1,015:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S
1
Line 673 ⟶ 1,034:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
</syntaxhighlight>
</lang>
 
 
 
=={{header|C}}==
Line 681 ⟶ 1,040:
{{trans|Fortran}}
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void pascaltriangle(unsigned int n)
Line 702 ⟶ 1,061:
pascaltriangle(8);
return 0;
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define D 32
Line 722 ⟶ 1,081:
int x[D] = {0, 1, 0}, y[D] = {0};
return pascals(x, y, 0);
}</langsyntaxhighlight>
 
===Adding previous row values===
 
<langsyntaxhighlight lang="c">void triangleC(int nRows) {
if (nRows <= 0) return;
int *prevRow = NULL;
Line 741 ⟶ 1,100:
}
free(prevRow);
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{trans|Fortran}}
Produces no output when n is less than or equal to zero.
 
<syntaxhighlight lang="csharp">using System;
 
namespace RosettaCode {
 
class PascalsTriangle {
 
public static void CreateTriangle(int n) {
if (n > 0) {
for (int i = 0; i < n; i++) {
int c = 1;
Console.Write(" ".PadLeft(2 * (n - 1 - i)));
for (int k = 0; k <= i; k++) {
Console.Write("{0}", c.ToString().PadLeft(3));
c = c * (i - k) / (k + 1);
}
Console.WriteLine();
}
}
}
 
public static void Main() {
CreateTriangle(8);
}
}
}</syntaxhighlight>
 
===Arbitrarily large numbers (BigInteger), arbitrary row selection===
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Numerics;
using System.Collections.Generic;
 
namespace RosettaCode
{
public static class PascalsTriangle
{
public static IEnumerable<BigInteger[]> GetTriangle(int quantityOfRows)
{
IEnumerable<BigInteger> range = Enumerable.Range(0, quantityOfRows).Select(num => new BigInteger(num));
return range.Select(num => GetRow(num).ToArray());
}
 
public static IEnumerable<BigInteger> GetRow(BigInteger rowNumber)
{
BigInteger denominator = 1;
BigInteger numerator = rowNumber;
 
BigInteger currentValue = 1;
for (BigInteger counter = 0; counter <= rowNumber; counter++)
{
yield return currentValue;
currentValue = BigInteger.Multiply(currentValue, numerator--);
currentValue = BigInteger.Divide(currentValue, denominator++);
}
yield break;
}
 
public static string FormatTriangleString(IEnumerable<BigInteger[]> triangle)
{
int maxDigitWidth = triangle.Last().Max().ToString().Length;
IEnumerable<string> rows = triangle.Select(arr =>
string.Join(" ", arr.Select(array => CenterString(array.ToString(), maxDigitWidth)) )
);
int maxRowWidth = rows.Last().Length;
return string.Join(Environment.NewLine, rows.Select(row => CenterString(row, maxRowWidth)));
}
 
private static string CenterString(string text, int width)
{
int spaces = width - text.Length;
int padLeft = (spaces / 2) + text.Length;
return text.PadLeft(padLeft).PadRight(width);
}
}
}</syntaxhighlight>
 
Example:
<syntaxhighlight lang="csharp">static void Main()
{
IEnumerable<BigInteger[]> triangle = PascalsTriangle.GetTriangle(20);
string output = PascalsTriangle.FormatTriangleString(triangle)
Console.WriteLine(output);
}</syntaxhighlight>
 
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
1 17 136 680 2380 6188 12376 19448 24310 24310 19448 12376 6188 2380 680 136 17 1
1 18 153 816 3060 8568 18564 31824 43758 48620 43758 31824 18564 8568 3060 816 153 18 1
1 19 171 969 3876 11628 27132 50388 75582 92378 92378 75582 50388 27132 11628 3876 969 171 19 1
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <algorithm>
#include<cstdio>
Line 823 ⟶ 1,294:
}
 
}</langsyntaxhighlight>
===C++11 (with dynamic and semi-static vectors)===
Constructs the whole triangle in memory before printing it. Uses vector of vectors as a 2D array with variable column size. Theoretically, semi-static version should work a little faster.
<langsyntaxhighlight lang="cpp">// Compile with -std=c++11
#include<iostream>
#include<vector>
Line 912 ⟶ 1,383:
}
 
</syntaxhighlight>
</lang>
===C++11 (with a class) ===
A full fledged example with a class definition and methods to retrieve data, worthy of the title object-oriented.
<langsyntaxhighlight lang="cpp">// Compile with -std=c++11
#include<iostream>
#include<vector>
Line 996 ⟶ 1,467:
}
 
</syntaxhighlight>
</lang>
=={{header|C sharp|C#}}==
{{trans|Fortran}}
Produces no output when n is less than or equal to zero.
 
<lang csharp>using System;
 
namespace RosettaCode {
 
class PascalsTriangle {
 
public static void CreateTriangle(int n) {
if (n > 0) {
for (int i = 0; i < n; i++) {
int c = 1;
Console.Write(" ".PadLeft(2 * (n - 1 - i)));
for (int k = 0; k <= i; k++) {
Console.Write("{0}", c.ToString().PadLeft(3));
c = c * (i - k) / (k + 1);
}
Console.WriteLine();
}
}
}
 
public static void Main() {
CreateTriangle(8);
}
}
}</lang>
 
=={{header|Clojure}}==
 
For n < 1, prints nothing, always returns nil. Copied from the Common Lisp implementation below, but with local functions and explicit tail-call-optimized recursion (recur).
<langsyntaxhighlight lang="lisp">(defn pascal [n]
(let [newrow (fn newrow [lst ret]
(if lst
Line 1,041 ⟶ 1,483:
(recur (dec n) (conj (newrow lst []) 1)))))]
(genrow n [1])))
(pascal 4)</langsyntaxhighlight>
And here's another version, using the ''partition'' function to produce the sequence of pairs in a row, which are summed and placed between two ones to produce the next row:
<langsyntaxhighlight lang="lisp">
(defn nextrow [row]
(vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] )))
Line 1,052 ⟶ 1,494:
(doseq [row triangle]
(println row))))
</syntaxhighlight>
</lang>
The ''assert'' form causes the ''pascal'' function to throw an exception unless the argument is (integral and) positive.
 
Here's a third version using the ''iterate'' function
<langsyntaxhighlight lang="lisp">
(def pascal
(iterate
Line 1,064 ⟶ 1,506:
(map (partial apply +) ,,,)))
[1]))
</syntaxhighlight>
</lang>
 
Another short version which returns an infinite pascal triangle as a list, using the iterate function.
 
<langsyntaxhighlight lang="lisp">
(def pascal
(iterate #(concat [1]
Line 1,074 ⟶ 1,516:
[1])
[1]))
</syntaxhighlight>
</lang>
 
One can then get the first n rows using the take function
 
<langsyntaxhighlight lang="lisp">
(take 10 pascal) ; returns a list of the first 10 pascal rows
</syntaxhighlight>
</lang>
 
Also, one can retrieve the nth row using the nth function
 
<langsyntaxhighlight lang="lisp">
(nth pascal 10) ;returns the nth row
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
This version assumes n is an integer and n >= 1. It efficiently computes binomial coefficients.
<langsyntaxhighlight lang="coffeescript">
pascal = (n) ->
width = 6
Line 1,120 ⟶ 1,562:
pascal(7)
 
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,133 ⟶ 1,575:
1 6 15 20 15 6 1
</pre>
 
=={{header|Commodore BASIC}}==
<syntaxhighlight lang="basic">10 INPUT "HOW MANY";N
20 IF N<1 THEN END
30 DIM C(N)
40 DIM D(N)
50 LET C(1)=1
60 LET D(1)=1
70 FOR J=1 TO N
80 FOR I=1 TO N-J+1
90 PRINT " ";
100 NEXT I
110 FOR I=1 TO J
120 PRINT C(I)" ";
130 NEXT I
140 PRINT
150 IF J=N THEN END
160 C(J+1)=1
170 D(J+1)=1
180 FOR I=1 TO J-1
190 D(I+1)=C(I)+C(I+1)
200 NEXT I
210 FOR I=1 TO J
220 C(I)=D(I)
230 NEXT I
240 NEXT J</syntaxhighlight>
 
Output:
<syntaxhighlight lang="text">RUN
HOW MANY? 8
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
READY.
</syntaxhighlight>
 
=={{header|Common Lisp}}==
To evaluate, call (pascal n). For n < 1, it simply returns nil.
 
<langsyntaxhighlight lang="lisp">(defun pascal (n)
(genrow n '(1)))
 
(defun genrow (n l)
(when (< 0plusp n)
(print l)
(genrow (1- n) (cons 1 (newrow l)))))
 
(defun newrow (l)
(if (> 2null (lengthrest l))
'(1)
(cons (+ (carfirst l) (cadrsecond l)) (newrow (cdr l)))))</lang>
(newrow (rest l)))))</syntaxhighlight>
 
An iterative solution with ''loop'', using ''nconc'' instead of ''collect'' to keep track of the last ''cons''. Otherwise, it would be necessary to traverse the list to do a ''(rplacd (last a) (list 1))''.
 
<langsyntaxhighlight lang="lisp">(defun pascal-next-row (a)
(loop :for q :in a
:and p = 0 :then q
:as s = (list (+ p q))
:nconc s :into a
:finally (rplacd s (list 1))
(return a)))
 
(defun pascal (n)
(loop :for a = (list 1) :then (pascal-next-row a)
:repeat n
:collect a))</langsyntaxhighlight>
 
Another iterative solution, this time using pretty-printing to automatically print the triangle in the shape of a triangle in the terminal. The print-pascal-triangle function computes and uses the length of the printed last row to decide how wide the triangle should be.
 
<syntaxhighlight lang="lisp">
(defun next-pascal-triangle-row (list)
`(1
,.(mapcar #'+ list (rest list))
1))
 
(defun pascal-triangle (number-of-rows)
(loop repeat number-of-rows
for row = '(1) then (next-pascal-triangle-row row)
collect row))
 
(defun print-pascal-triangle (number-of-rows)
(let* ((triangle (pascal-triangle number-of-rows))
(max-row-length (length (write-to-string (first (last triangle))))))
(format t
(format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" max-row-length)
triangle)))
</syntaxhighlight>
 
For example:
 
<syntaxhighlight lang="lisp">(print-pascal-triangle 4)</syntaxhighlight>
<syntaxhighlight lang="text">
1
1 1
1 2 1
1 3 3 1
</syntaxhighlight>
<syntaxhighlight lang="lisp">(print-pascal-triangle 8)</syntaxhighlight>
<syntaxhighlight lang="text">
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
</syntaxhighlight>
 
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
<syntaxhighlight lang="oberon2">
MODULE PascalTriangle;
IMPORT StdLog, DevCommanders, TextMappers;
 
TYPE
Expansion* = POINTER TO ARRAY OF LONGINT;
 
PROCEDURE Show*(e: Expansion);
VAR
i: INTEGER;
BEGIN
i := 0;
WHILE (i < LEN(e)) & (e[i] # 0) DO
StdLog.Int(e[i]);
INC(i)
END;
StdLog.Ln
END Show;
 
PROCEDURE GenFor*(p: LONGINT): Expansion;
VAR
expA,expB: Expansion;
i,j: LONGINT;
PROCEDURE Swap(VAR x,y: Expansion);
VAR
swap: Expansion;
BEGIN
swap := x; x := y; y := swap
END Swap;
BEGIN
ASSERT(p >= 0);
NEW(expA,p + 2);NEW(expB,p + 2);
FOR i := 0 TO p DO
IF i = 0 THEN expA[0] := 1
ELSE
FOR j := 0 TO i DO
IF j = 0 THEN
expB[j] := expA[j]
ELSE
expB[j] := expA[j - 1] + expA[j]
END
END;
Swap(expA,expB)
END;
END;
expB := NIL; (* for the GC *)
RETURN expA
END GenFor;
 
 
PROCEDURE Do*;
VAR
s: TextMappers.Scanner;
exp: Expansion;
BEGIN
s.ConnectTo(DevCommanders.par.text);
s.SetPos(DevCommanders.par.beg);
s.Scan;
WHILE (~s.rider.eot) DO
IF (s.type = TextMappers.char) & (s.char = '~') THEN
RETURN
ELSIF (s.type = TextMappers.int) THEN
exp := GenFor(s.int);
Show(exp)
END;
s.Scan
END
END Do;
 
END PascalTriangle.
</syntaxhighlight>
<pre>Execute: ^Q PascalTriangle.Do 0 1 2 3 4 5 6 7 8 9 10 11 12~</pre>
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
</pre>
 
=={{header|D}}==
===Less functional Version===
<langsyntaxhighlight lang="d">int[][] pascalsTriangle(in int rows) pure nothrow {
auto tri = new int[][rows];
foreach (r; 0 .. rows) {
Line 1,191 ⟶ 1,810:
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]);
}</langsyntaxhighlight>
===More functional Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
auto pascal() pure nothrow {
Line 1,203 ⟶ 1,822:
void main() {
pascal.take(5).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]</pre>
Line 1,211 ⟶ 1,830:
Their difference are the initial line and the operation that act on the line element to produce next line.
The following is a generic pascal's triangle implementation for positive number of lines output (n).
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.array, std.format;
 
string Pascal(alias dg, T, T initValue)(int n) {
Line 1,252 ⟶ 1,871:
foreach (i; [16])
writef(sierpinski(i));
}</langsyntaxhighlight>
{{out}}
<pre> 1
Line 1,287 ⟶ 1,906:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">
import 'dart:io';
 
Line 1,330 ⟶ 1,949:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">program PascalsTriangle;
 
procedure Pascal(r:Integer);
Line 1,353 ⟶ 1,972:
begin
Pascal(9);
end.</langsyntaxhighlight>
 
=={{header|DWScript}}==
Doesn't print anything for negative or null values.
<langsyntaxhighlight lang="delphi">procedure Pascal(r : Integer);
var
i, c, k : Integer;
Line 1,371 ⟶ 1,990:
end;
 
Pascal(9);</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 1,387 ⟶ 2,006:
So as not to bother with text layout, this implementation generates a HTML fragment. It uses a single mutable array, appending one 1 and adding to each value the preceding value.
 
<langsyntaxhighlight lang="e">def pascalsTriangle(n, out) {
def row := [].diverge(int)
out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>")
Line 1,406 ⟶ 2,025:
}
out.print("</table>")
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">def out := <file:triangle.html>.textWriter()
try {
pascalsTriangle(15, out)
Line 1,414 ⟶ 2,033:
out.close()
}
makeCommand("yourFavoriteWebBrowser")("triangle.html")</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
numfmt 0 4
proc pascal n . .
r[] = [ 1 ]
for i to n
rn[] = [ ]
l = 0
for j to n - len r[]
write " "
.
for r in r[]
write r
rn[] &= l + r
l = r
.
print ""
rn[] &= l
swap r[] rn[]
.
.
pascal 13
</syntaxhighlight>
 
=={{header|Eiffel}}==
 
<langsyntaxhighlight lang="eiffel">
note
description : "Prints pascal's triangle"
Line 1,520 ⟶ 2,163:
--Contains all already calculated lines
end
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Pascal do
def triangle(n), do: triangle(n,[1])
Line 1,534 ⟶ 2,177:
end
 
Pascal.triangle(8)</langsyntaxhighlight>
 
{{out}}
Line 1,546 ⟶ 2,189:
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
</pre>
 
=={{header|Emacs Lisp}}==
===Using mapcar and append, returing a list of rows===
<syntaxhighlight lang="lisp">(require 'cl-lib)
 
(defun next-row (row)
(cl-mapcar #'+ (cons 0 row)
(append row '(0))))
 
(defun triangle (row rows)
(if (= rows 0)
'()
(cons row (triangle (next-row row) (- rows 1)))))</syntaxhighlight>
 
{{Out}}
Call the function from the REPL, IELM:
<pre>
ELISP> (triangle (list 1) 6)
((1)
(1 1)
(1 2 1)
(1 3 3 1)
(1 4 6 4 1)
(1 5 10 10 5 1))
</pre>
===Translation from Pascal===
<syntaxhighlight lang="lisp">(defun pascal (r)
(dotimes (i r)
(let ((c 1))
(dotimes (k (+ i 1))
(princ (format "%d " c))
(setq c (/ (* c (- i k))
(+ k 1))))
(terpri))))</syntaxhighlight>
{{Out}}
From the REPL:
<pre>
ELISP> (princ (pascal 6))
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
</pre>
===Returning a string===
Same as the translation from Pascal, but now returning a string.
<syntaxhighlight lang="lisp">(defun pascal (r)
(let ((out ""))
(dotimes (i r)
(let ((c 1))
(dotimes (k (+ i 1))
(setq out (concat out (format "%d " c)))
(setq c (/ (* c (- i k))
(+ k 1))))
(setq out (concat out "\n"))))
out))</syntaxhighlight>
{{Out}}
Now, since this one returns a string, it is possible to insert the result in the current buffer:
 
<pre>
(insert (pascal 6))
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
</pre>
 
=={{header|Erlang}}==
 
<langsyntaxhighlight lang="erlang">
-import(lists).
-export([pascal/1]).
Line 1,559 ⟶ 2,271:
[H|_] = L,
[lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,569 ⟶ 2,281:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM PASCAL_TRIANGLE
 
Line 1,587 ⟶ 2,299:
PASCAL(9)
END PROGRAM
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,603 ⟶ 2,315:
=={{header|Euphoria}}==
===Summing from Previous Rows===
<langsyntaxhighlight Euphorialang="euphoria">sequence row
row = {}
for m = 1 to 10 do
Line 1,612 ⟶ 2,324:
print(1,row)
puts(1,'\n')
end for</langsyntaxhighlight>
 
{{Out}}
Line 1,627 ⟶ 2,339:
{1,9,36,84,126,126,84,36,9,1}
</pre>
 
=={{header|Excel}}==
===LAMBDA===
 
Binding the names PASCAL and BINCOEFF to the following lambda expressions in the Name Manager of the Excel WorkBook, to define Pascal's triangle in terms of binomial coefficients:
 
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function])
 
{{Works with|Office 365 betas 2021}}
<syntaxhighlight lang="lisp">PASCAL
=LAMBDA(n,
BINCOEFF(n - 1)(
SEQUENCE(1, n, 0, 1)
)
)
 
 
BINCOEFF
=LAMBDA(n,
LAMBDA(k,
QUOTIENT(FACT(n), FACT(k) * FACT(n - k))
)
)</syntaxhighlight>
 
{{Out}}
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="11" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=PASCAL(A2)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
| C
| D
| E
| F
| G
| H
| I
| J
| K
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
| style="font-style:italic" | Row number
| colspan="10" style="font-weight:bold" | PASCAL's TRIANGLE
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:right; font-style:italic" | 1
| style="text-align:center; background-color:#cbcefb" | 1
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
| style="text-align:right; font-style:italic" | 2
| style="text-align:center" | 1
| style="text-align:center" | 1
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
| style="text-align:right; font-style:italic" | 3
| style="text-align:center" | 1
| style="text-align:center" | 2
| style="text-align:center" | 1
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
| style="text-align:right; font-style:italic" | 4
| style="text-align:center" | 1
| style="text-align:center" | 3
| style="text-align:center" | 3
| style="text-align:center" | 1
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
| style="text-align:right; font-style:italic" | 5
| style="text-align:center" | 1
| style="text-align:center" | 4
| style="text-align:center" | 6
| style="text-align:center" | 4
| style="text-align:center" | 1
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 7
| style="text-align:right; font-style:italic" | 6
| style="text-align:center" | 1
| style="text-align:center" | 5
| style="text-align:center" | 10
| style="text-align:center" | 10
| style="text-align:center" | 5
| style="text-align:center" | 1
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 8
| style="text-align:right; font-style:italic" | 7
| style="text-align:center" | 1
| style="text-align:center" | 6
| style="text-align:center" | 15
| style="text-align:center" | 20
| style="text-align:center" | 15
| style="text-align:center" | 6
| style="text-align:center" | 1
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 9
| style="text-align:right; font-style:italic" | 8
| style="text-align:center" | 1
| style="text-align:center" | 7
| style="text-align:center" | 21
| style="text-align:center" | 35
| style="text-align:center" | 35
| style="text-align:center" | 21
| style="text-align:center" | 7
| style="text-align:center" | 1
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 10
| style="text-align:right; font-style:italic" | 9
| style="text-align:center" | 1
| style="text-align:center" | 8
| style="text-align:center" | 28
| style="text-align:center" | 56
| style="text-align:center" | 70
| style="text-align:center" | 56
| style="text-align:center" | 28
| style="text-align:center" | 8
| style="text-align:center" | 1
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 11
| style="text-align:right; font-style:italic" | 10
| style="text-align:center" | 1
| style="text-align:center" | 9
| style="text-align:center" | 36
| style="text-align:center" | 84
| style="text-align:center" | 126
| style="text-align:center" | 126
| style="text-align:center" | 84
| style="text-align:center" | 36
| style="text-align:center" | 9
| style="text-align:center" | 1
|}
 
Or defining the whole triangle as a single grid, by binding the name TRIANGLE to an additional lambda:
 
<syntaxhighlight lang="lisp">TRIANGLE
=LAMBDA(n,
LET(
ixs, SEQUENCE(n, n, 0, 1),
x, MOD(ixs, n),
y, QUOTIENT(ixs, n),
IF(x <= y,
BINCOEFF(y)(x),
""
)
)
)</syntaxhighlight>
 
{{Out}}
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="11" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=TRIANGLE(10)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
| C
| D
| E
| F
| G
| H
| I
| J
| K
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
| style="font-style:italic" |
| colspan="10" style="font-weight:bold" | PASCAL's TRIANGLE
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="font-style:italic" |
| style="text-align:center; background-color:#cbcefb" | 1
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
| style="font-style:italic" |
| style="text-align:center" | 1
| style="text-align:center" | 1
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
| style="font-style:italic" |
| style="text-align:center" | 1
| style="text-align:center" | 2
| style="text-align:center" | 1
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
| style="font-style:italic" |
| style="text-align:center" | 1
| style="text-align:center" | 3
| style="text-align:center" | 3
| style="text-align:center" | 1
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
| style="font-style:italic" |
| style="text-align:center" | 1
| style="text-align:center" | 4
| style="text-align:center" | 6
| style="text-align:center" | 4
| style="text-align:center" | 1
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 7
| style="font-style:italic" |
| style="text-align:center" | 1
| style="text-align:center" | 5
| style="text-align:center" | 10
| style="text-align:center" | 10
| style="text-align:center" | 5
| style="text-align:center" | 1
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 8
| style="font-style:italic" |
| style="text-align:center" | 1
| style="text-align:center" | 6
| style="text-align:center" | 15
| style="text-align:center" | 20
| style="text-align:center" | 15
| style="text-align:center" | 6
| style="text-align:center" | 1
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 9
| style="font-style:italic" |
| style="text-align:center" | 1
| style="text-align:center" | 7
| style="text-align:center" | 21
| style="text-align:center" | 35
| style="text-align:center" | 35
| style="text-align:center" | 21
| style="text-align:center" | 7
| style="text-align:center" | 1
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 10
| style="font-style:italic" |
| style="text-align:center" | 1
| style="text-align:center" | 8
| style="text-align:center" | 28
| style="text-align:center" | 56
| style="text-align:center" | 70
| style="text-align:center" | 56
| style="text-align:center" | 28
| style="text-align:center" | 8
| style="text-align:center" | 1
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 11
| style="font-style:italic" |
| style="text-align:center" | 1
| style="text-align:center" | 9
| style="text-align:center" | 36
| style="text-align:center" | 84
| style="text-align:center" | 126
| style="text-align:center" | 126
| style="text-align:center" | 84
| style="text-align:center" | 36
| style="text-align:center" | 9
| style="text-align:center" | 1
|}
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let rec nextrow l =
match l with
| [] -> []
Line 1,641 ⟶ 2,699:
printf "%s" (i.ToString() + ", ")
printfn "%s" "\n"
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Line 1,647 ⟶ 2,705:
This implementation works by summing the previous line content. Result for n < 1 is the same as for n == 1.
 
<langsyntaxhighlight lang="factor">USING: grouping kernel math sequences ;
 
: (pascal) ( seq -- newseq )
Line 1,653 ⟶ 2,711:
 
: pascal ( n -- seq )
1 - { { 1 } } swap [ (pascal) ] times ;</langsyntaxhighlight>
 
It works as:
 
<langsyntaxhighlight lang="factor">5 pascal .
{ { 1 } { 1 1 } { 1 2 1 } { 1 3 3 1 } { 1 4 6 4 1 } }</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,692 ⟶ 2,750:
}
}
</syntaxhighlight>
</lang>
 
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">1.1 S OLD(1)=1; T %4.0, 1, !
1.2 F N=1,10; D 2
1.3 Q
 
2.1 S NEW(1)=1
2.2 F X=1,N; S NEW(X+1)=OLD(X)+OLD(X+1)
2.3 F X=1,N+1; D 3
2.4 T !
 
3.1 S OLD(X)=NEW(X)
3.2 T %4.0, OLD(X)</syntaxhighlight>
{{output}}
<pre>
= 1
= 1= 1
= 1= 2= 1
= 1= 3= 3= 1
= 1= 4= 6= 4= 1
= 1= 5= 10= 10= 5= 1
= 1= 6= 15= 20= 15= 6= 1
= 1= 7= 21= 35= 35= 21= 7= 1
= 1= 8= 28= 56= 70= 56= 28= 8= 1
= 1= 9= 36= 84= 126= 126= 84= 36= 9= 1
= 1= 10= 45= 120= 210= 252= 210= 120= 45= 10= 1
</pre>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: init ( n -- )
here swap cells erase 1 here ! ;
: .line ( n -- )
Line 1,705 ⟶ 2,790:
: pascal ( n -- )
dup init 1 .line
1 ?do i next i 1+ .line loop ;</langsyntaxhighlight>
This is a bit more efficient.
{{trans|C}}
<langsyntaxhighlight lang="forth">: PascTriangle
cr dup 0
?do
Line 1,715 ⟶ 2,800:
;
 
13 PascTriangle</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
Prints nothing for n<=0. Output formatting breaks down for n>20
<langsyntaxhighlight lang="fortran">PROGRAM Pascals_Triangle
 
CALL Print_Triangle(8)
Line 1,745 ⟶ 2,830:
END DO
 
END SUBROUTINE Print_Triangle</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub pascalTriangle(n As UInteger)
Line 1,784 ⟶ 2,869:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,802 ⟶ 2,887:
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
</pre>
 
=={{header|Frink}}==
This version takes a little effort to automatically format the tree based upon the width of the largest numbers in the bottom row. It automatically calculates this easily using Frink's builtin function for efficiently calculating (even large) binomial coefficients with cached factorials and binary splitting.
<syntaxhighlight lang="frink">
pascal[rows] :=
{
widest = length[toString[binomial[rows-1, (rows-1) div 2]]]
for row = 0 to rows-1
{
line = repeat[" ", round[(rows-row)* (widest+1)/2]]
for col = 0 to row
line = line + padRight[binomial[row, col], widest+1, " "]
 
println[line]
}
}
 
pascal[10]
</syntaxhighlight>
 
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
</pre>
 
Line 1,807 ⟶ 2,926:
=== Summing from Previous Rows ===
{{trans|Scala}}
<langsyntaxhighlight lang="funl">import lists.zip
 
def
pascal( 1 ) = [1]
pascal( n ) = [1] + map( (a, b) -> a + b, zip(pascal(n-1), pascal(n-1).tail()) ) + [1]</langsyntaxhighlight>
 
=== Combinations ===
{{trans|Haskell}}
<langsyntaxhighlight lang="funl">import integers.choose
 
def pascal( n ) = [choose( n - 1, k ) | k <- 0..n-1]</langsyntaxhighlight>
 
=== Pascal's Triangle ===
<langsyntaxhighlight lang="funl">def triangle( height ) =
width = max( map(a -> a.toString().length(), pascal(height)) )
 
Line 1,830 ⟶ 2,949:
println( map(a -> format('%' + width + 'd ', a), pascal(n)).mkString() )
 
triangle( 10 )</langsyntaxhighlight>
 
{{out}}
Line 1,845 ⟶ 2,964:
1 9 36 84 126 126 84 36 9 1
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Pascal%27s_triangle}}
 
'''Solution'''
 
[[File:Fōrmulæ - Pascal's triangle 01.png]]
 
'''Test case'''
 
[[File:Fōrmulæ - Pascal's triangle 02.png]]
 
[[File:Fōrmulæ - Pascal's triangle 03.png]]
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">Pascal := function(n)
local i, v;
v := [1];
Line 1,865 ⟶ 2,998:
# [ 1, 6, 15, 20, 15, 6, 1 ]
# [ 1, 7, 21, 35, 35, 21, 7, 1 ]
# [ 1, 8, 28, 56, 70, 56, 28, 8, 1 ]</langsyntaxhighlight>
 
=={{header|Go}}==
No output for n < 1. Otherwise, output formatted left justified.
<syntaxhighlight lang="go">
<lang go>
package main
 
Line 1,912 ⟶ 3,045:
printTriangle(4)
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,924 ⟶ 3,057:
=== Recursive ===
In the spirit of the Haskell "think in whole lists" solution here is a list-driven, minimalist solution:
<langsyntaxhighlight lang="groovy">def pascal
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }</langsyntaxhighlight>
However, this solution is horribly inefficient (O(''n''**2)). It slowly grinds to a halt on a reasonably powerful PC after about line 25 of the triangle.
 
Test program:
<langsyntaxhighlight lang="groovy">def count = 15
(1..count).each { n ->
printf ("%2d:", n); (0..(count-n)).each { print " " }; pascal(n).each{ printf("%6d ", it) }; println ""
}</langsyntaxhighlight>
 
{{out}}
Line 1,952 ⟶ 3,085:
 
=={{header|GW-BASIC}}==
<langsyntaxhighlight lang="qbasic">10 INPUT "Number of rows? ",R
20 FOR I=0 TO R-1
30 C=1
Line 1,960 ⟶ 3,093:
70 NEXT
80 PRINT
90 NEXT</langsyntaxhighlight>
 
Output:
Line 1,982 ⟶ 3,115:
similar function
 
<langsyntaxhighlight lang="haskell">zapWith :: (a -> a -> a) -> [a] -> [a] -> [a]
zapWith f xs [] = xs
zapWith f [] ys = ys
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys</langsyntaxhighlight>
 
Now we can shift a list and add it to itself, extending it by keeping
the ends:
 
<langsyntaxhighlight lang="haskell">extendWith f [] = []
extendWith f xs@(x:ys) = x : zapWith f xs ys</langsyntaxhighlight>
 
And for the whole (infinite) triangle, we just iterate this operation,
starting with the first row:
 
<langsyntaxhighlight lang="haskell">pascal = iterate (extendWith (+)) [1]</langsyntaxhighlight>
 
For the first ''n'' rows, we just take the first ''n'' elements from this
list, as in
 
<langsyntaxhighlight lang="haskell">*Main> take 6 pascal
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]</langsyntaxhighlight>
 
A shorter approach, plagiarized from [http://www.haskell.org/haskellwiki/Blow_your_mind]
<langsyntaxhighlight lang="haskell">-- generate next row from current row
nextRow row = zipWith (+) ([0] ++ row) (row ++ [0])
 
-- returns the first n rows
pascal = iterate nextRow [1]</langsyntaxhighlight>
 
Alternatively, using list comprehensions:
 
<syntaxhighlight lang="haskell">
pascal :: [[Integer]]
pascal =
(1 : [ 0 | _ <- head pascal])
: [zipWith (+) (0:row) row | row <- pascal]
</syntaxhighlight>
 
<syntaxhighlight lang="haskell">
*Pascal> take 5 <$> (take 5 $ triangle)
[[1,0,0,0,0],[1,1,0,0,0],[1,2,1,0,0],[1,3,3,1,0],[1,4,6,4,1]]
</syntaxhighlight>
 
With binomial coefficients:
<langsyntaxhighlight lang="haskell">fac = product . enumFromTo 1
 
binCoef n k = (fac n) `div` ((fac k) * (fac $ (n - k))
 
pascal n = map (binCoef(fmap $. nbinCoef) -<*> 1)enumFromTo [0) ..n-1] pred</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="haskell">*Main> putStr $ unlines $ map unwords $ map (map show) $ pascal 10
1
1 1
Line 2,031 ⟶ 3,177:
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
</syntaxhighlight>
</lang>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest"> CALL Pascal(30)
 
SUBROUTINE Pascal(rows)
Line 2,048 ⟶ 3,194:
ENDDO
ENDDO
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The code below is slightly modified from the library version of pascal which prints 0's to the full width of the carpet.
It also presents the data as an isoceles triangle.
<langsyntaxhighlight Iconlang="icon">link math
procedure main(A)
Line 2,071 ⟶ 3,218:
write()
}
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 2,097 ⟶ 3,244:
 
=={{header|IDL}}==
<langsyntaxhighlight IDLlang="idl">Pro Pascal, n
;n is the number of lines of the triangle to be displayed
r=[1]
Line 2,113 ⟶ 3,260:
print, r
 
End</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "PascalTr.bas"
110 TEXT 80
120 LET ROW=12
130 FOR I=0 TO ROW
140 LET C=1
150 PRINT TAB(37-I*3);
160 FOR K=0 TO I
170 PRINT USING " #### ":C;
180 LET C=C*(I-K)/(K+1)
190 NEXT
200 PRINT
210 NEXT</syntaxhighlight>
 
{{out}}
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1</pre>
 
=={{header|ivy}}==
<syntaxhighlight lang="ivy">
op pascal N = transp (0 , iota N) o.! -1 , iota N
pascal 5
1 0 0 0 0 0
1 1 0 0 0 0
1 2 1 0 0 0
1 3 3 1 0 0
1 4 6 4 1 0
1 5 10 10 5 1
</syntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> !~/~ i.5
1 0 0 0 0
1 1 0 0 0
1 2 1 0 0
1 3 3 1 0
1 4 6 4 1</langsyntaxhighlight>
 
<langsyntaxhighlight lang="j"> ([: ":@-.&0"1 !~/~)@i. 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1</langsyntaxhighlight>
 
<langsyntaxhighlight lang="j"> (-@|. |."_1 [: ":@-.&0"1 !~/~)@i. 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1</langsyntaxhighlight>
 
However, multi-digit numbers take up additional space, which looks slightly odd. But we can work around that by adding additional padding and shifting the lines a bit more:
 
<syntaxhighlight lang=J> (|."_1~ 0-3*i.@-@#) ;@((<'%6d') sprintf each -.&0)"1 !~/~i.10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
</syntaxhighlight>
 
Also... when we mix positive and negative numbers it stops being a triangle:
 
<syntaxhighlight lang=J> i:5
_5 _4 _3 _2 _1 0 1 2 3 4 5
!~/~i:5
1 0 0 0 0 1 _5 15 _35 70 _126
_4 1 0 0 0 1 _4 10 _20 35 _56
6 _3 1 0 0 1 _3 6 _10 15 _21
_4 3 _2 1 0 1 _2 3 _4 5 _6
1 _1 1 _1 1 1 _1 1 _1 1 _1
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 1 2 1 0 0 0
0 0 0 0 0 1 3 3 1 0 0
0 0 0 0 0 1 4 6 4 1 0
0 0 0 0 0 1 5 10 10 5 1
!/~i:5
1 _4 6 _4 1 0 0 0 0 0 0
0 1 _3 3 _1 0 0 0 0 0 0
0 0 1 _2 1 0 0 0 0 0 0
0 0 0 1 _1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1
_5 _4 _3 _2 _1 0 1 2 3 4 5
15 10 6 3 1 0 0 1 3 6 10
_35 _20 _10 _4 _1 0 0 0 1 4 10
70 35 15 5 1 0 0 0 0 1 5
_126 _56 _21 _6 _1 0 0 0 0 0 1</syntaxhighlight>
 
 
 
See the [[Talk:Pascal's_triangle#J_Explanation|talk page]] for explanation of earlier version
Line 2,144 ⟶ 3,378:
===Summing from Previous Rows===
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java">import java.util.ArrayList;
...//class definition, etc.
public static void genPyrN(int rows){
Line 2,164 ⟶ 3,398:
System.out.println(thisRow);
}
}</langsyntaxhighlight>
 
===Combinations===
This method is limited to 21 rows because of the limits of <tt>long</tt>. Calling <tt>pas</tt> with an argument of 22 or above will cause intermediate math to wrap around and give false answers.
<langsyntaxhighlight lang="java">public class Pas{
public static void main(String[] args){
//usage
Line 2,194 ⟶ 3,428:
return ans;
}
}</langsyntaxhighlight>
 
===Using arithmetic calculation of each row element ===
This method is limited to 30 rows because of the limits of integer calculations (probably when calculating the multiplication). If m is declared as long then 62 rows can be printed.
<langsyntaxhighlight lang="java">
public class Pascal {
private static void printPascalLine (int n) {
Line 2,218 ⟶ 3,452:
}
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
 
===ES5===
====Imperative====
 
{{works with|SpiderMonkey}}
{{works with|V8}}
<langsyntaxhighlight lang="javascript">// Pascal's triangle object
function pascalTriangle (rows) {
 
Line 2,297 ⟶ 3,529:
// Display 8 row triangle in base 16
tri = new pascalTriangle(8);
tri.print(16);</langsyntaxhighlight>
Output:
<pre>$ d8 pascal.js
Line 2,311 ⟶ 3,543:
1 5 a a 5 1
1 6 f 14 f 6 1
1 7 15 23 23 15 7 1</pre>
</pre>
 
 
====Functional====
 
{{Trans|Haskell}}
<syntaxhighlight lang="javascript">(function (n) {
 
<lang JavaScript>(function (n) {
'use strict';
 
// PASCAL TRIANGLE --------------------------------------------------------
// A Pascal triangle of n rows
 
// pascal :: Int -> [[Int]]
function pascal(n) {
return rangefoldl(1,function n - 1(a) {
.reduce(functionvar xs = (a.slice(-1)[0]; // Previous {row
return append(a, var lstPreviousRow = a.slice[zipWith(-1)[0];
function (a, b) {
return a + b;
},
append([0], xs),
append(xs, [0])
)]);
}, [
[1] // Initial seed row
], enumFromTo(1, n - 1));
};
 
return a
.concat(
[zipWith(
function (a, b) {
return a + b
},
[0].concat(lstPreviousRow),
lstPreviousRow.concat(0)
)]
);
}, [[1]]);
}
 
// GENERIC FUNCTIONS ------------------------------------------------------
 
// (++) :: [a] -> [a] -> [a]
function append(xs, ys) {
return xs.concat(ys);
};
 
// enumFromTo :: Int -> Int -> [Int]
// GENERIC FUNCTIONS
function enumFromTo(m, n) {
return Array.from({
length: Math.floor(n - m) + 1
}, function (_, i) {
return m + i;
});
};
 
// foldl :: (b -> a -> b) -> b -> [a] -> b
function foldl(f, a, xs) {
return xs.reduce(f, a);
};
 
// foldr (a -> b -> b) -> b -> [a] -> b
function foldr(f, a, xs) {
return xs.reduceRight(f, a);
};
 
// map :: (a -> b) -> [a] -> [b]
function map(f, xs) {
return xs.map(f);
};
 
// min :: Ord a => a -> a -> a
function min(a, b) {
return b < a ? b : a;
};
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
function zipWith(f, xs, ys) {
return xsArray.length === ys.length ? from({
length: min(xs.map(function (xlength, iys.length) {
}, function return f(x_, ys[i]); {
}return f(xs[i], ys[i]);
}) : undefined;
};
 
// TEST and FORMAT --------------------------------------------------------
// range :: Int -> Int -> [Int]
function range(m, n) {
return Array.apply(null, Array(n - m + 1))
.map(function (x, i) {
return m + i;
});
}
 
// TEST
var lstTriangle = pascal(n);
 
 
// FORMAT OUTPUT AS WIKI TABLE
 
// [[a]] -> bool -> s -> s
function wikiTable(lstRows, blnHeaderRow, strStyle) {
return '{| class="wikitable" ' + (strStyle ? 'style="' + strStyle +
strStyle'"' ?: 'style="') + strStylelstRows.map(function +(lstRow, '"'iRow) : ''{
) + lstRows.map(function (lstRow, var strDelim = blnHeaderRow && !iRow) {? '!' : '|';
varreturn strDelim'\n|-\n' =+ ((blnHeaderRowstrDelim &&+ !iRow)' ? '!' :+ '|'lstRow.map(function (v); {
 
return '\n|-\n' + strDelim + ' ' + lstRow.map(function (
v) {
return typeof v === 'undefined' ? ' ' : v;
})
Line 2,387 ⟶ 3,631:
 
var lstLastLine = lstTriangle.slice(-1)[0],
lngBase = (lstLastLine.length * 2) - 1,
nWidth = lstLastLine.reduce(function (a, x) {
var d = x.toString()
Line 2,394 ⟶ 3,638:
}, 1) * lngBase;
 
return [wikiTable(lstTriangle.map(function (lst) {
return lst.join(';;')
wikiTable(
lstTriangle .mapsplit(function (lst';') {;
return lst.join(';;'})
.map(function (line, i) .split(';');{
}var lstPad = Array((lngBase - line.length) / 2);
return lstPad.map(function concat(line, i) {
var .concat(lstPad = Array((lngBase - line.length) / 2);
}), false, 'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
return lstPad.concat(line)
'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n');
.concat(lstPad);
})(7);</syntaxhighlight>
}),
{{Out}}
false,
'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
'em;table-layout:fixed;'
),
 
JSON.stringify(lstTriangle)
].join('\n\n');
})(7);</lang>
 
Output:
 
{| class="wikitable" style="text-align:center;width:26em;height:26em;table-layout:fixed;"
|-
Line 2,433 ⟶ 3,667:
|}
 
<langsyntaxhighlight JavaScriptlang="javascript">[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1],[1,6,15,20,15,6,1]]</langsyntaxhighlight>
 
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
"use strict";
 
// ---------------- PASCAL'S TRIANGLE ----------------
 
// pascal :: Generator [[Int]]
<lang JavaScript>(() => {
'useconst strict';pascal = () =>
iterate(
xs => zipWith(
a => b => a + b
)(
[0, ...xs]
)(
[...xs, 0]
)
)([1]);
 
// pascal :: Int -> [[Int]]
let pascal = n =>
range(1, n - 1)
.reduce(a => {
let lstPreviousRow = a.slice(-1)[0];
 
// ---------------------- TEST -----------------------
return a
// main :: IO ()
.concat([zipWith((a, b) => a + b,
const main = () =>
[0].concat(lstPreviousRow),
showPascal(
lstPreviousRow.concat(0)
take(10)]);(
}, [ pascal()
[1])
]);
 
// GENERIC FUNCTIONS
 
// IntshowPascal ->:: [[Int]] -> Maybe Int -> [Int]String
letconst rangeshowPascal = (m, n, step)xs => {
const let dw = last(step || 1xs) * .join(n >= m ?" 1 : -1").length;
return Array.from({
length: Math.floor((n - m) / d) + 1
}, (_, i) => m + (i * d));
},
 
return xs.map(
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith = (f, xs, ys) => center(w)(" ")(ys.join(" "))
xs.length === ys.length ? ()
xs.mapjoin((x, i) => f(x, ys[i])"\n");
};
) : undefined;
 
// TEST
return pascal(7)
.reduceRight((a, x) => {
let strIndent = a.indent;
 
// ---------------- GENERIC FUNCTIONS ----------------
return {
rows: strIndent + x
.map(n => (' ' + n).slice(-4))
.join('') + '\n' + a.rows,
indent: strIndent + ' '
};
}, {
rows: '',
indent: ''
}).rows;
})();</lang>
 
// center :: Int -> Char -> String -> String
const center = n =>
// Size of space -> filler Char ->
// String -> Centered String
c => s => {
const gap = n - s.length;
 
return 0 < gap ? (() => {
const
margin = c.repeat(Math.floor(gap / 2)),
dust = c.repeat(gap % 2);
 
return `${margin}${s}${margin}${dust}`;
})() : s;
};
 
 
// iterate :: (a -> a) -> a -> Gen [a]
const iterate = f =>
// An infinite list of repeated
// applications of f to x.
function* (x) {
let v = x;
 
while (true) {
yield v;
v = f(v);
}
};
 
 
// last :: [a] -> a
const last = xs =>
0 < xs.length ? xs.slice(-1)[0] : undefined;
 
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : Array.from({
length: n
}, () => {
const x = xs.next();
 
return x.done ? [] : [x.value];
}).flat();
 
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// A list constructed by zipping with a
// custom function, rather than with the
// default tuple constructor.
xs => ys => xs.map(
(x, i) => f(x)(ys[i])
).slice(
0, Math.min(xs.length, ys.length)
);
 
 
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1</pre>
 
====Recursive====
<syntaxhighlight lang="javascript">
const aux = n => {
if(n <= 1) return [1]
const prevLayer = aux(n - 1)
const shifted = [0, ...prevLayer]
return shifted.map((x, i) => (prevLayer[i] || 0) + x)
}
const pascal = n => {
for(let i = 1; i <= n; i++) {
console.log(aux(i).join(' '))
}
}
pascal(8)
</syntaxhighlight>
{{Out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
</pre>
====Recursive - memoized====
<syntaxhighlight lang="javascript">
const aux = (() => {
const layers = [[1], [1]]
return n => {
if(layers[n]) return layers[n]
const prevLayer = aux(n - 1)
const shifted = [0, ...prevLayer]
layers[n] = shifted.map((x, i) => (prevLayer[i] || 0) + x)
return layers[n]
}
})()
const pascal = n => {
for(let i = 1; i <= n; i++) {
console.log(aux(i).join(' '))
}
}
pascal(8)
</syntaxhighlight>
 
=={{header|jq}}==
Line 2,505 ⟶ 3,842:
each corresponding to a row of the Pascal triangle.
The implementation avoids any arithmetic except addition.
<langsyntaxhighlight lang="jq"># pascal(n) for n>=0; pascal(0) emits an empty stream.
def pascal(n):
def _pascal: # input: the previous row
Line 2,515 ⟶ 3,852:
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] | _pascal
end;
if n <= 0 then empty else [1] | _pascal end ;</langsyntaxhighlight>
'''Example''':
pascal(5)
{{ Out }}
<langsyntaxhighlight lang="sh">$ jq -c -n -f pascal_triangle.jq
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]</langsyntaxhighlight>
 
'''Using recurse/1'''
 
Here is an equivalent implementation that uses the built-in filter, recurse/1, instead of the inner function.
<langsyntaxhighlight lang="jq">def pascal(n):
if n <= 0 then empty
else [1]
Line 2,537 ⟶ 3,874:
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1]
end)
end;</langsyntaxhighlight>
 
=={{header|Julia}}==
 
Line 2,547 ⟶ 3,885:
while x<=n
for a=0:x
print(binomial(x,a)," ")
end
println("")
Line 2,554 ⟶ 3,892:
end
<pre>
pascal(45)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
</pre>
 
Another solution using matrix exponentiation.
 
<syntaxhighlight lang="julia">
iround(x) = round(Int64, x)
 
triangle(n) = iround.(exp(diagm(-1=> 1:n)))
 
function pascal(n)
t=triangle(n)
println.(join.([filter(!iszero, t[i,:]) for i in 1:(n+1)], " "))
end
 
</syntaxhighlight>
 
{{Out}}
 
<pre>
pascal(5)
1
1 1
11
1 2 1
121
1 3 3 1
1331
1 4 6 4 1
14641
1 5 10 10 5 1
</pre>
 
Yet another solution using a static vector
 
<syntaxhighlight lang="julia">
function pascal(n)
(n<=0) && error("Pascal trinalge can not have zero or negative rows")
r=Vector{Int}(undef,n)
pr=Vector{Int}(undef,n)
pr[1]=r[1]=1
println(@view pr[1])
for i=2:n
r[1]=r[i]=1
for j=2:i-1
r[j]=pr[j-1]+pr[j]
end
println(join(view(r,1:i), " "))
r,pr=pr,r
end
end
</syntaxhighlight>
 
{{Out}}
 
<pre>
pascal(8)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
</pre>
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
pascal:{(x-1){+':x,0}\1}
pascal 6
Line 2,572 ⟶ 3,970:
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="kotlin">fun pas(rows: Int) {
for (i in 0..rows - 1) {
for (j in 0..i)
Line 2,592 ⟶ 3,990:
}
 
fun main(args: Array<String>) = pas(args[0].toInt())</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
1) Based on this expression of pascalian binomial:
 
Cnp = [n*(n-1)...(n-p+1)]/[p*(p-1)...2*1]
 
2) we define the following function:
 
{def C
{lambda {:n :p}
{/ {* {S.serie :n {- :n :p -1} -1}}
{* {S.serie :p 1 -1}}}}}
 
{C 16 8}
-> 12870
 
3) Writing
 
1{S.map {lambda {:n} {br}1
{S.map {C :n} {S.serie 1 {- :n 1}}} 1}
{S.serie 2 16}}
displays:
 
1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">input "How much rows would you like? "; n
dim a$(n)
 
Line 2,613 ⟶ 4,052:
next i
 
end</langsyntaxhighlight>
 
=={{header|Locomotive Basic}}==
 
<langsyntaxhighlight lang="locobasic">10 CLS
20 INPUT "Number of rows? ", rows:GOSUB 40
30 END
Line 2,628 ⟶ 4,067:
100 PRINT
110 NEXT
120 RETURN</langsyntaxhighlight>
 
Output:
Line 2,644 ⟶ 4,083:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to pascal :n
if :n = 1 [output [1]]
localmake "a pascal :n-1
Line 2,650 ⟶ 4,089:
end
 
for [i 1 10] [print pascal :i]</langsyntaxhighlight>
 
=={{header|Logtalk}}==
Our implementation will have an object <code>pascals</code> with work done in the method <code>triangle/2</code>. We will be caching results for time efficiency at the cost of space efficiency,and the <code>reset/0</code> method will flush that cache should it grow to be a problem. The resulting object looks like this:
<syntaxhighlight lang="logtalk">
:- object(pascals).
 
:- uses(integer, [plus/3, succ/2]).
 
:- public(reset/0).
 
reset :-
retractall(triangle_(_,_,_)).
:- private(triangle_/3).
:- dynamic(triangle_/3).
 
:- public(triangle/2).
 
triangle(N, Lines) :-
triangle(N, _, DiffLines),
difflist::as_list(DiffLines, Lines).
 
% Shortcut with cached value if it exists.
triangle(N, Line, DiffLines) :- triangle_(N, Line, DiffLines), !.
 
triangle(N, Line, DiffLines) :-
succ(N0, N),
triangle(N0, Line0, DiffLines0),
ZL = [0|Line0],
list::append(Line0, [0], ZR),
meta::map(plus, ZL, ZR, Line),
difflist::add(Line, DiffLines0, DiffLines),
asserta(triangle_(N, Line, DiffLines)).
 
triangle(1, [1], [[1]|X]-X).
 
:- end_object.
</syntaxhighlight>
 
{{Out}}
 
Using the SWI-Prolog back-end:
 
<pre>
?- logtalk_load([meta(loader), types(loader), pascals], [optimize(on)]).
% messages elided
true.
 
?- pascals::triangle(17, Ls), logtalk::print_message(information, user, Ls).
% - [1]
% - [1,1]
% - [1,2,1]
% - [1,3,3,1]
% - [1,4,6,4,1]
% - [1,5,10,10,5,1]
% - [1,6,15,20,15,6,1]
% - [1,7,21,35,35,21,7,1]
% - [1,8,28,56,70,56,28,8,1]
% - [1,9,36,84,126,126,84,36,9,1]
% - [1,10,45,120,210,252,210,120,45,10,1]
% - [1,11,55,165,330,462,462,330,165,55,11,1]
% - [1,12,66,220,495,792,924,792,495,220,66,12,1]
% - [1,13,78,286,715,1287,1716,1716,1287,715,286,78,13,1]
% - [1,14,91,364,1001,2002,3003,3432,3003,2002,1001,364,91,14,1]
% - [1,15,105,455,1365,3003,5005,6435,6435,5005,3003,1365,455,105,15,1]
% - [1,16,120,560,1820,4368,8008,11440,12870,11440,8008,4368,1820,560,120,16,1]
Ls = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4|...], [1, 5, 10|...], [1, 6|...], [1|...], [...|...]|...].
 
?-
</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function nextrow(t)
local ret = {}
Line 2,667 ⟶ 4,177:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1);
 
f(3);</langsyntaxhighlight>
1
1 1
1 2 1
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">n=7;
<lang Mathematica>Column[StringReplace[ToString /@ Replace[MatrixExp[SparseArray[
Column[StringReplace[ToString /@ Replace[MatrixExp[SparseArray[
{Band[{2,1}] -> Range[n-1]},{n,n}]],{x__,0..}->{x},2] ,{"{"|"}"|","->" "}], Center]</lang>
{Band[{2,1}] -> Range[n-1]},{n,n}]],{x__,0..}->{x},2] ,{"{"|"}"|","->" "}], Center]</syntaxhighlight>
[[File:MmaPascal.png]]
[[File:MmaPascal.png]]
 
A more graphical output with arrows would involve the plotting functionality with Graph[]:
<syntaxhighlight lang="mathematica">nmax := 10;
pascal[nmax_] := Module[
{vals = Table[Binomial[n, k], {n, 0, nmax}, {k, 0, n}],
ids = Table[{n, k}, {n, 0, nmax}, {k, 0, n}],
labels, left, right, leftright, edgeLabels
},
labels = Flatten[Thread /@ (Thread[ids -> vals]), 1];
left = DeleteCases[Flatten[Flatten[ids, 1] /. {n_, k_} /; (n >= k + 1) :> {{n, k + 1} -> {n + 1, k + 1}}, 1], _?NumberQ];
right = DeleteCases[Flatten[Flatten[ids, 1] /. {n_, k_} /; (n > k) :> {{n, k} -> {n + 1, k + 1}}, 1], _?NumberQ];
leftright = DeleteCases[left \[Union] right, _ -> {b_, _} /; b > nmax];
edgeLabels = (# -> Style["+", Medium] & /@ leftright);
Graph[Flatten[ids, 1], leftright
, VertexLabels -> MapAt[Placed[#, Center] &, labels, {All, 2}]
, GraphLayout -> "SpringEmbedding"
, VertexSize -> 0.8, EdgeLabels -> edgeLabels
, PlotLabel -> "Pascal's Triangle"
]
];
pascal[nmax]
</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
A matrix containing the pascal triangle can be obtained this way:
<syntaxhighlight lang MATLAB="matlab">pascal(n);</langsyntaxhighlight>
 
<pre>>> pascal(6)
Line 2,700 ⟶ 4,233:
 
The binomial coefficients can be extracted from the Pascal triangle in this way:
<langsyntaxhighlight MATLABlang="matlab"> binomCoeff = diag(rot90(pascal(n)))', </langsyntaxhighlight>
 
<pre>>> for k=1:6,diag(rot90(pascal(k)))', end
Line 2,750 ⟶ 4,283:
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
<lang maxima>sjoin(v, j) := apply(sconcat, rest(join(makelist(j, length(v)), v)))$
sjoin(v, j) := apply(sconcat, rest(join(makelist(j, length(v)), v)))$
 
display_pascal_triangle(n) := for i from 0 thru 6 do disp(sjoin(makelist(binomial(i, j), j, 0, i), " "));
Line 2,761 ⟶ 4,295:
"1 4 6 4 1"
"1 5 10 10 5 1"
"1 6 15 20 15 6 1" */</lang>
</syntaxhighlight>
 
 
=={{header|Metafont}}==
Line 2,768 ⟶ 4,302:
(The formatting starts to be less clear when numbers start to have more than two digits)
 
<langsyntaxhighlight lang="metafont">vardef bincoeff(expr n, k) =
save ?;
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor )
Line 2,785 ⟶ 4,319:
 
pascaltr(4);
end</langsyntaxhighlight>
 
=={{header|Microsoft Small Basic}}==
{{trans|GW-BASIC}}
<syntaxhighlight lang="microsoftsmallbasic">
TextWindow.Write("Number of rows? ")
r = TextWindow.ReadNumber()
For i = 0 To r - 1
c = 1
For k = 0 To i
TextWindow.CursorLeft = (k + 1) * 4 - Text.GetLength(c)
TextWindow.Write(c)
c = c * (i - k) / (k + 1)
EndFor
TextWindow.WriteLine("")
EndFor
</syntaxhighlight>
 
Output:
<pre>
Number of rows? 7
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
</pre>
 
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE Pascal;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
 
PROCEDURE PrintLine(n : INTEGER);
VAR
buf : ARRAY[0..63] OF CHAR;
m,j : INTEGER;
BEGIN
IF n<1 THEN RETURN END;
m := 1;
WriteString("1 ");
FOR j:=1 TO n-1 DO
m := m * (n - j) DIV j;
FormatString("%i ", buf, m);
WriteString(buf)
END;
WriteLn
END PrintLine;
 
PROCEDURE Print(n : INTEGER);
VAR i : INTEGER;
BEGIN
FOR i:=1 TO n DO
PrintLine(i)
END
END Print;
 
BEGIN
Print(10);
 
ReadChar
END Pascal.</syntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,828 ⟶ 4,425:
end n_
return fac /*calc. factorial*/
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,848 ⟶ 4,445:
 
(pascal.nial)
<langsyntaxhighlight lang="nial">factorial is recur [ 0 =, 1 first, pass, product, -1 +]
combination is fork [ > [first, second], 0 first,
/ [factorial second, * [factorial - [second, first], factorial first] ]
]
pascal is transpose each combination cart [pass, pass] tell</langsyntaxhighlight>
Using it
<langsyntaxhighlight lang="nial">|loaddefs 'pascal.nial'
|pascal 5</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import sequtils, strutils
 
proc pascalprintPascalTriangle(n: int) =
## Print a Pascal triangle.
var row = @[1]
for r in 1..n:
echo row
row = zip(row & @[0], @[0] & row).mapIt(int, it[0] + it[1])
 
# Build the triangle.
pascal(10)</lang>
var triangle: seq[seq[int]]
triangle.add @[1]
for _ in 1..<n:
triangle.add zip(triangle[^1] & @[0], @[0] & triangle[^1]).mapIt(it[0] + it[1])
 
# Build the lines to display.
let length = len($max(triangle[^1])) # Maximum length of number.
var lines: seq[string]
for row in triangle:
lines.add row.mapIt(($it).center(length)).join(" ")
 
# Display the lines.
let lineLength = lines[^1].len # Length of largest line (the last one).
for line in lines:
echo line.center(lineLength)
 
printPascalTriangle(10)</syntaxhighlight>
 
{{out}}
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1 </pre>
 
A more optimized solution that doesn't require importing, but produces, naturally, uglier output, would look like this:
<syntaxhighlight lang="nim">const ROWS = 10
const TRILEN = toInt(ROWS * (ROWS + 1) / 2) # Sum of arth progression
var triangle = newSeqOfCap[Natural](TRILEN) # Avoid reallocations
 
proc printPascalTri(row: Natural, result: var seq[Natural]) =
add(result, 1)
for i in 2..row-1: add(result, result[^row] + result[^(row-1)])
add(result, 1)
 
echo result[^row..^1]
if row + 1 <= ROWS: printPascalTri(row + 1, result)
 
printPascalTri(1, triangle)</syntaxhighlight>
 
{{out}}
<pre>@[1]
@[1, 1]
@[1, 2, 1]
@[1, 3, 3, 1]
@[1, 4, 6, 4, 1]
@[1, 5, 10, 10, 5, 1]
@[1, 6, 15, 20, 15, 6, 1]
@[1, 7, 21, 35, 35, 21, 7, 1]
@[1, 8, 28, 56, 70, 56, 28, 8, 1]
@[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]</pre>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">(* generate next row from current row *)
let next_row row =
List.map2 (+) ([0] @ row) (row @ [0])
Line 2,879 ⟶ 4,529:
if i = n then []
else row :: loop (i+1) (next_row row)
in loop 0 [1]</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">function pascaltriangle(h)
for i = 0:h-1
for k = 0:h-i
Line 2,894 ⟶ 4,544:
endfunction
 
pascaltriangle(4);</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 2,900 ⟶ 4,550:
No result if n <= 0
 
<langsyntaxhighlight Oforthlang="oforth">: pascal(n) [ 1 ] #[ dup println dup 0 + 0 rot + zipWith(#+) ] times(n) drop ;</langsyntaxhighlight>
 
{{out}}
Line 2,918 ⟶ 4,568:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {NextLine Xs}
{List.zip 0|Xs {Append Xs [0]}
Line 2,948 ⟶ 4,598:
end
in
{PrintTriangle {Triangle 5}}</langsyntaxhighlight>
 
For n = 0, prints nothing. For negative n, throws an exception.
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">pascals_triangle(N)= {
my(row=[],prevrow=[]);
for(x=1,N,
Line 2,966 ⟶ 4,617:
print(row);
);
}</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program PascalsTriangle(output);
 
procedure Pascal(r : Integer);
Line 2,989 ⟶ 4,640:
begin
Pascal(9)
end.</langsyntaxhighlight>
Output:
<pre>% ./PascalsTriangle
Line 3,005 ⟶ 4,656:
=={{header|Perl}}==
These functions perform as requested in the task: they print out the first ''n'' lines. If ''n'' <= 0, they print nothing. The output is simple (no fancy formatting).
<langsyntaxhighlight lang="perl">sub pascal {
my $rows = shift;
my @next = (1);
Line 3,012 ⟶ 4,663:
@next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1);
}
}</langsyntaxhighlight>
 
If you want more than 68 rows, then use either "use bigint" or "use Math::GMP qw/:constant/" inside the function to enable bigints. We can also use a binomial function which will expand to bigints if many rows are requested:
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/binomial/;
sub pascal {
my $rows = shift;
Line 3,022 ⟶ 4,673:
print join(" ", map { binomial($n,$_) } 0 .. $n), "\n";
}
}</langsyntaxhighlight>
 
Here is a non-obvious version using bignum, which is limited to the first 23 rows because of the algorithm used:
<langsyntaxhighlight lang="perl">use bignum;
sub pascal_line { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 }
sub pascal { print "@{[map -+-$_, pascal_line $_]}\n" for 0..$_[0]-1 }</langsyntaxhighlight>
 
This triangle is build using the 'sock' or 'hockey stick' pattern property. Here I use the word tartaglia and not pascal because in my country it's called after the Niccolò Fontana, known also as Tartaglia. A full graphical implementation of 16 properties that can be found in the triangle can be found at mine [https://github.com/LorenzoTa/Tartaglia-s-triangle Tartaglia's triangle]
=={{header|Perl 6}}==
{{works with|rakudo|2015-10-03}}
=== using a lazy sequence generator ===
 
<syntaxhighlight lang="perl">
The following routine returns a lazy list of lines using the sequence operator (<tt>...</tt>). With a lazy result you need not tell the routine how many you want; you can just use a slice subscript to get the first N lines:
#!/usr/bin/perl
<lang perl6>sub pascal {
use strict;
[1], { [0, |$_ Z+ |$_, 0] } ... *
use warnings;
{
my @tartaglia ;
sub tartaglia {
my ($x,$y) = @_;
if ($x == 0 or $y == 0) { $tartaglia[$x][$y]=1 ; return 1};
my $ret ;
foreach my $yps (0..$y){
$ret += ( $tartaglia[$x-1][$yps] || tartaglia($x-1,$yps) );
}
$tartaglia[$x][$y] = $ret;
return $ret;
}
}
sub tartaglia_row {
my $y = shift;
my $x = 0;
my @row;
$row[0] = &tartaglia($x,$y+1);
foreach my $pos (0..$y-1) {push @row, tartaglia(++$x,--$y)}
return @row;
}
.say for pascal[^10];</lang>
 
One problem with the routine above is that it might recalculate the sequence each time you call it. Slightly more idiomatic would be to define the sequence as a lazy constant. Here we use the <tt>@</tt> sigil to indicate that the sequence should cache its values for reuse, and use an explicit parameter <tt>$prev</tt> for variety:
 
for (0..5) {print join ' ', tartaglia_row($_),"\n"}
<lang perl6>constant @pascal = [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... *;
print "\n\n";
.say for @pascal[^10];</lang>
 
Since we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error.
 
print tartaglia(3,3),"\n";
=== recursive ===
my @third = tartaglia_row(5);
print "@third\n";
</syntaxhighlight>
 
which output
{{trans|Haskell}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
 
<lang perl6>multi sub pascal (1) { $[1] }
multi sub pascal (Int $n where 2..*) {
my @rows = pascal $n - 1;
|@rows, [0, |@rows[*-1] Z+ |@rows[*-1], 0 ];
}
.say for pascal 10;</lang>
 
20
Non-positive inputs throw a multiple-dispatch error.
1 5 10 10 5 1
 
</pre>
=== iterative ===
 
{{trans|Perl}}
<lang perl6>sub pascal ($n where $n >= 1) {
say my @last = 1;
for 1 .. $n - 1 -> $row {
@last = 1, |map({ @last[$_] + @last[$_ + 1] }, 0 .. $row - 2), 1;
say @last;
}
}
pascal 10;</lang>
 
Non-positive inputs throw a type check error.
 
{{Output}}
<pre>[1]
[1 1]
[1 2 1]
[1 3 3 1]
[1 4 6 4 1]
[1 5 10 10 5 1]
[1 6 15 20 15 6 1]
[1 7 21 35 35 21 7 1]
[1 8 28 56 70 56 28 8 1]
[1 9 36 84 126 126 84 36 9 1]</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence row = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">row</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
for m = 1 to 13 do
<span style="color: #008080;">for</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">13</span> <span style="color: #008080;">do</span>
row = row & 1
<span style="color: #000000;">row</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">row</span> <span style="color: #0000FF;">&</span> <span style="color: #000000;">1</span>
for n=length(row)-1 to 2 by -1 do
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">row</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
row[n] += row[n-1]
<span style="color: #000000;">row</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">row</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,repeat(' ',(13-m)*2))
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,(</span><span style="color: #000000;">13</span><span style="color: #0000FF;">-</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
for i=1 to length(row) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">row</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
printf(1," %3d",row[i])
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %3d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">row</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
puts(1,'\n')
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">)</span>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre style="font-size: 8px">
Line 3,120 ⟶ 4,766:
 
"Reflected" Pascal's triangle, it uses symmetry property to "mirror" second part. It determines even and odd strings. automatically.
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
<?php
//Author Ivan Gavryshin @dcc0
Line 3,167 ⟶ 4,814:
?>
</syntaxhighlight> =={{header|PHP}}==
</lang>
<syntaxhighlight lang="php">function pascalsTriangle($num){
 
=={{header|PHP}}==
<lang php>function pascalsTriangle($num){
$c = 1;
$triangle = Array();
Line 3,192 ⟶ 4,837:
}
echo '<br>';
}</langsyntaxhighlight>
1
1 1
Line 3,202 ⟶ 4,847:
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">
%Author: Petar Kabashki
spatr([]) = [].
spatr([_|T]) = A, T = [] => A = [].
spatr([H|T]) = A, T = [TH|_] => A = [H+TH] ++ spatr(T).
 
table
patr(0) = [1].
patr(1) = [1, 1].
patr(N) = A, N > 1 => Apre = patr(N-1), A = [1] ++ spatr(Apre) ++ [1].
 
foreach(I in 0 .. 10) println(patr(I)) end.
</syntaxhighlight>
<syntaxhighlight lang="picat">
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]
[1,5,10,10,5,1]
[1,6,15,20,15,6,1]
[1,7,21,35,35,21,7,1]
[1,8,28,56,70,56,28,8,1]
[1,9,36,84,126,126,84,36,9,1]
[1,10,45,120,210,252,210,120,45,10,1]
</syntaxhighlight>
 
=={{header|PicoLisp}}==
{{trans|C}}
<syntaxhighlight lang="picolisp">(de pascalTriangle (N)
(for I N
(space (* 2 (- N I)))
(let C 1
(for K I
(prin (align 3 C) " ")
(setq C (*/ C (- I K) K)) ) )
(prinl) ) )</syntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare (t, u)(40) fixed binary;
declare (i, n) fixed binary;
Line 3,220 ⟶ 4,904:
t = u;
end;
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="text">
1
1 1
Line 3,234 ⟶ 4,918:
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
{{trans|C}}
<lang PicoLisp>(de pascalTriangle (N)
(for I N
(space (* 2 (- N I)))
(let C 1
(for K I
(prin (align 3 C) " ")
(setq C (*/ C (- I K) K)) ) )
(prinl) ) )</lang>
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion">printpascal = (n) :
if (n < 1) :
1 print
Line 3,265 ⟶ 4,938:
.
 
printpascal(read number integer)</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">
$Infinity = 1
$NewNumbers = $null
Line 3,333 ⟶ 5,006:
$Infinity++
}
</syntaxhighlight>
</lang>
 
Save the above code to a .ps1 script file and start it by calling its name and providing N.
Line 3,362 ⟶ 5,035:
=={{header|Prolog}}==
Difference-lists are used to make quick append.
<langsyntaxhighlight Prologlang="prolog">pascal(N) :-
pascal(1, N, [1], [[1]|X]-X, L),
maplist(my_format, L).
Line 3,398 ⟶ 5,071:
my_writef(X) :-
writef(' %5r', [X]).
</syntaxhighlight>
</lang>
 
Output :
<langsyntaxhighlight Prologlang="prolog"> ?- pascal(15).
1
1 1
Line 3,419 ⟶ 5,092:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
true.
</syntaxhighlight>
</lang>
===An alternative===
The above use of difference lists is a really innovative example of late binding. Here's an alternative source which, while possibly not as efficient (or as short) as the previous example, may be a little easier to read and understand.
<syntaxhighlight lang="prolog">%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Produce a pascal's triangle of depth N
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Prolog is declarative. The predicate pascal/3 below says that to produce
% a row of depth N, we can do so by first producing the row at depth(N-1),
% and then adding the paired values in that row. The triangle is produced
% by prepending the row at N-1 to the preceding rows as recursion unwinds.
% The triangle produced by pascal/3 is upside down and lacks the last row,
% so pascal/2 prepends the last row to the triangle and reverses it.
% Finally, pascal/1 produces the triangle, iterates each row and prints it.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pascal_row([V], [V]). % No more value pairs to add
pascal_row([V0, V1|T], [V|Rest]) :- % Add values from preceding row
V is V0 + V1, !, pascal_row([V1|T], Rest). % Drops initial value (1).
 
pascal(1, [1], []). % at depth 1, this row is [1] and no preceding rows.
pascal(N, [1|ThisRow], [Last|Preceding]) :- % Produce a row of depth N
succ(N0, N), % N is the successor to N0
pascal(N0, Last, Preceding), % Get the previous row
!, pascal_row(Last, ThisRow). % Calculate this row from the previous
 
pascal(N, Triangle) :-
pascal(N, Last, Rows), % Retrieve row at depth N and preceding rows
!, reverse([Last|Rows], Triangle). % Add last row to triangle and reverse order
 
pascal(N) :-
pascal(N, Triangle), member(Row, Triangle), % Iterate and write each row
write(Row), nl, fail.
pascal(_).</syntaxhighlight>
*Output*:
<syntaxhighlight lang="prolog">?- pascal(5).
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]</syntaxhighlight>
 
=={{header|PureBasic}}==
 
<langsyntaxhighlight PureBasiclang="purebasic">Procedure pascaltriangle( n.i)
For i= 0 To n
Line 3,438 ⟶ 5,150:
Parameter.i = Val(ProgramParameter(0))
pascaltriangle(Parameter);
Input()</langsyntaxhighlight>
 
=={{header|Python}}==
===Procedural===
<lang python>def pascal(n):
<syntaxhighlight lang="python">def pascal(n):
"""Prints out n rows of Pascal's triangle.
It returns False for failure and True for success."""
Line 3,449 ⟶ 5,162:
print row
row=[l+r for l,r in zip(row+k,k+row)]
return n>=1</langsyntaxhighlight>
 
Or,or by creating a scan function:
<langsyntaxhighlight lang="python">def scan(op, seq, it):
a = []
result = it
Line 3,468 ⟶ 5,181:
 
for row in pascal(4):
print(row)</langsyntaxhighlight>
 
===Functional===
 
Deriving finite and non-finite lists of pascal rows from a simple '''nextPascal''' step function:
 
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''Pascal's triangle'''
 
from itertools import (accumulate, chain, islice)
from operator import (add)
 
 
# nextPascal :: [Int] -> [Int]
def nextPascal(xs):
'''A row of Pascal's triangle
derived from a preceding row.'''
return list(
map(add, [0] + xs, xs + [0])
)
 
 
# pascalTriangle :: Generator [[Int]]
def pascalTriangle():
'''A non-finite stream of
Pascal's triangle rows.'''
return iterate(nextPascal)([1])
 
 
# finitePascalRows :: Int -> [[Int]]
def finitePascalRows(n):
'''The first n rows of Pascal's triangle.'''
return accumulate(
chain(
[[1]], range(1, n)
),
lambda a, _: nextPascal(a)
)
 
 
# ------------------------ TESTS -------------------------
# main :: IO ()
def main():
'''Test of two different approaches:
- taking from a non-finite stream of rows,
- or constructing a finite list of rows.'''
print('\n'.join(map(
showPascal,
[
islice(
pascalTriangle(), # Non finite,
7
),
finitePascalRows(7) # finite.
]
)))
 
 
# showPascal :: [[Int]] -> String
def showPascal(xs):
'''Stringification of a list of
Pascal triangle rows.'''
ys = list(xs)
 
def align(w):
return lambda ns: center(w)(
' '
)(' '.join(map(str, ns)))
 
w = len(' '.join((map(str, ys[-1]))))
return '\n'.join(map(align(w), ys))
 
 
# ----------------------- GENERIC ------------------------
 
# center :: Int -> Char -> String -> String
def center(n):
'''String s padded with c to approximate centre,
fitting in but not truncated to width n.'''
def go(c, s):
qr = divmod(n - len(s), 2)
q = qr[0]
return (q * c) + s + ((q + qr[1]) * c)
 
return lambda c: lambda s: go(c, s)
 
 
# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
'''An infinite list of repeated
applications of f to x.
'''
def go(x):
v = x
while True:
yield v
v = f(v)
 
return go
 
 
# MAIN ---
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1</pre>
 
=={{header|q}}==
<syntaxhighlight lang="q">
<lang q>
pascal:{(x-1){0+':x,0}\1}
pascal 5
Line 3,479 ⟶ 5,310:
1 3 3 1
1 4 6 4 1
</syntaxhighlight>
</lang>
 
=={{header|Qi}}==
{{trans|Haskell}}
<syntaxhighlight lang="qi">
<lang Qi>
(define iterate
_ _ 0 -> []
Line 3,493 ⟶ 5,324:
(define pascal
N -> (iterate next-row [1] N))
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
The behaviour of <code>pascal</code> for values less than 1 is the same as its behaviour for 1.
 
<syntaxhighlight lang="quackery"> [ over size -
space swap of
swap join ] is justify ( $ n --> )
 
[ witheach
[ number$
5 justify echo$ ]
cr ] is echoline ( [ --> )
[ [] 0 rot 0 join
witheach
[ tuck +
rot join swap ]
drop ] is nextline ( [ --> [ )
[ ' [ 1 ] swap
1 - times
[ dup echoline
nextline ]
echoline ] is pascal ( n --> )
16 pascal</syntaxhighlight>
 
{{out}}
 
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
</pre>
 
=={{header|R}}==
{{trans|Octave}}
<langsyntaxhighlight Rlang="r">pascalTriangle <- function(h) {
for(i in 0:(h-1)) {
s <- ""
Line 3,506 ⟶ 5,384:
print(s)
}
}</langsyntaxhighlight>
 
Here's an R version:
 
<langsyntaxhighlight Rlang="r">pascalTriangle <- function(h) {
lapply(0:h, function(i) choose(i, 0:i))
}</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 3,518 ⟶ 5,396:
Iterative version by summing rows up to <math>n</math>.
 
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (pascal n)
Line 3,530 ⟶ 5,408:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-10-03}}
=== using a lazy sequence generator ===
 
The following routine returns a lazy list of lines using the sequence operator (<tt>...</tt>). With a lazy result you need not tell the routine how many you want; you can just use a slice subscript to get the first N lines:
<syntaxhighlight lang="raku" line>sub pascal {
[1], { [0, |$_ Z+ |$_, 0] } ... *
}
.say for pascal[^10];</syntaxhighlight>
 
One problem with the routine above is that it might recalculate the sequence each time you call it. Slightly more idiomatic would be to define the sequence as a lazy constant. Here we use the <tt>@</tt> sigil to indicate that the sequence should cache its values for reuse, and use an explicit parameter <tt>$prev</tt> for variety:
 
<syntaxhighlight lang="raku" line>constant @pascal = [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... *;
.say for @pascal[^10];</syntaxhighlight>
 
Since we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error.
 
=== recursive ===
 
{{trans|Haskell}}
 
<syntaxhighlight lang="raku" line>multi sub pascal (1) { $[1] }
multi sub pascal (Int $n where 2..*) {
my @rows = pascal $n - 1;
|@rows, [0, |@rows[*-1] Z+ |@rows[*-1], 0 ];
}
.say for pascal 10;</syntaxhighlight>
 
Non-positive inputs throw a multiple-dispatch error.
 
=== iterative ===
 
{{trans|Perl}}
<syntaxhighlight lang="raku" line>sub pascal ($n where $n >= 1) {
say my @last = 1;
for 1 .. $n - 1 -> $row {
@last = 1, |map({ @last[$_] + @last[$_ + 1] }, 0 .. $row - 2), 1;
say @last;
}
}
pascal 10;</syntaxhighlight>
 
Non-positive inputs throw a type check error.
 
{{Output}}
<pre>[1]
[1 1]
[1 2 1]
[1 3 3 1]
[1 4 6 4 1]
[1 5 10 10 5 1]
[1 6 15 20 15 6 1]
[1 7 21 35 35 21 7 1]
[1 8 28 56 70 56 28 8 1]
[1 9 36 84 126 126 84 36 9 1]</pre>
 
=={{header|RapidQ}}==
Line 3,545 ⟶ 5,484:
RapidQ does not require simple variables to be declared before use.
 
<langsyntaxhighlight lang="rapidq">DEFINT values(100) = {0,1}
 
INPUT "Number of rows: "; nrows
Line 3,556 ⟶ 5,495:
NEXT i
PRINT
NEXT row</langsyntaxhighlight>
 
===Using binary coefficients===
{{trans|BASIC}}
<langsyntaxhighlight lang="rapidq">INPUT "Number of rows: "; nrows
FOR row = 0 TO nrows-1
c = 1
Line 3,569 ⟶ 5,508:
NEXT i
PRINT
NEXT row</langsyntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="red">Red[]
pascal-triangle: function [
n [ integer! ] "number of rows"
][
row: make vector! [ 1 ]
loop n [
print row
left: copy row
right: copy row
insert left 0
append right 0
row: left + right
]
]</syntaxhighlight>
Output:
<pre>
pascal-triangle 7
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
</pre>
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">2 elements i j
: pascalTriangle
cr dup
[ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop
;
13 pascalTriangle</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 3,583 ⟶ 5,549:
generated (without wrapping) in a screen window with a width of 620 characters.
 
If the number (of rows) specified is negative, &nbsp; the output is written to a (disk) file
instead. &nbsp; Triangles with over a &nbsp; 1,000 &nbsp; rows have easily been easily created. &nbsp;
<br>The output file created (that is written to disk) is named &nbsp; &nbsp; '''PASCALS.n'''
&nbsp; &nbsp; where &nbsp; '''n''' &nbsp; is the absolute value of the number entered.
 
Line 3,594 ⟶ 5,560:
:::* &nbsp; Tartaglia's triangle
:::* &nbsp; Yang Hui's triangle
<langsyntaxhighlight lang="rexx">/*REXX program displays (or writes to a file) Pascal's triangle (centered/formatted).*/
numeric digits 3000 /*be able to handle gihugeic triangles.*/
parse arg nn . /*obtain the optional argument from CL.*/
if nn=='' | nn=="," then nn=10 10 /*Not specified? Then use the default.*/
Nn= abs(nn) /*N is the number of rows in triangle.*/
w= length( !(Nn-1) / % !(Nn%2) / % !(Nn - 1 -N n%2) ) /*W: the width of the biggest integer. */
@.ww= (n-1;) * (W + $.=@.;1) + unity=right(1, w) /*defaultsWW: " " rows &" lines;triangle's alignedlast unityrow.*/
@.= 1; $.= @.; unity= right(1, w) /*defaults rows & lines; aligned unity.*/
/* [↓] build rows of Pascals' triangle*/
do r=1 for N;do r=1 for n; rm=r-1 rm= r-1 /*Note: the first column is always 1.*/
do c=2 to rm; cm= c-1 /*build the rest of the columns in row.*/
@.r.c= @.rm.cm + @.rm.c /*assign value to a specific row & col.*/
$.r = $.r right(@.r.c, w) /*and construct a line for output (row)*/
end /*c*/ end /*c*/ /* [↑] C is the column being built.*/
if r\==1 then $.r= $.r unity /*for rows≥2, append a trailing "1".*/
end /*r*/ end /*r*/ /* [↑] R is the row being built.*/
/* [↑] WIDTH: for nicely looking line.*/
width=length($.N) do r=1 for n; $$= center($.r, ww) /*widthcenter ofthis theparticular lastPascals' (output)row. line (row)*/
if nn>0 then say $$ /*SAY if NN is /*if NN<0positive, output is written to aelse file.*/
do r=1 for N; else $$=center($call lineout 'PASCALS.r'n, width) $$ /*centerwrite this particular PascalsPascal's row. ───► a file.*/
end /*r*/
if nn>0 then say $$ /*SAY if NN is positive, else */
else call lineout 'PASCALS.'n, $$ /*write this Pascal's row ───► a file.*/
end /*r*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure; !=1; do j=2 to arg(1); != !*j; end /*j*/; return ! /*compute factorial*/</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 11 </tt>}}
<pre>
1
Line 3,633 ⟶ 5,598:
1 10 45 120 210 252 210 120 45 10 1
</pre>
'''{{out|output''' |text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 22 </tt>}}
 
(Output shown at &nbsp; <big>'''<sup>4</sup>/<sub>5</sub>'''</big> &nbsp; size.)
Line 3,662 ⟶ 5,627:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
row = 5
for i = 0 to row - 1
Line 3,673 ⟶ 5,638:
see nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,682 ⟶ 5,647:
1 4 6 4 1
</pre>
 
=={{header|RPL}}==
« 0 SWAP '''FOR''' n
"" 0 n '''FOR''' p
n p COMB + " " +
'''NEXT'''
n 1 + DISP
'''NEXT'''
7 FREEZE
» '<span style="color:blue">PASCAL</span>' STO
 
8 <span style="color:blue">PASCAL</span>
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 …
</pre>
RPL screens are limited to 22 characters.
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def pascal(n)
raise ArgumentError, "must be positive." if n < 1
yield ar = [1]
(n-1).times do
ar.unshift(0).push(0) # tack a zero on both ends
yield ar = ar.each_cons(2).map{|a, b| a + b } (&:sum)
end
end
pascal(8){|row| puts row.join(" ").center(20)}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,708 ⟶ 5,698:
Or for more or less a translation of the two line Haskell version (with inject being abused a bit I know):
 
<langsyntaxhighlight lang="ruby">def next_row(row) ([0] + row).zip(row + [0]).collect {|l,r| l + r } end
 
def pascal(n) n.times.inject([1]) {|x,_| next_row x } end
 
8.times{|i| p pascal(i)}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,726 ⟶ 5,716:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">input "number of rows? ";r
for i = 0 to r - 1
c = 1
Line 3,735 ⟶ 5,725:
next
print
next</langsyntaxhighlight>Output:
<pre>Number of rows? ?5
1
Line 3,743 ⟶ 5,733:
1 4 6 4 1</pre>
 
=={{header|ScalaRust}}==
{{trans|C}}
Simple recursive row definition:
<syntaxhighlight lang="rust">
<lang scala>
fn pascal_triangle(n: u64)
def tri(row:Int):List[Int] = { row match {
{
case 1 => List(1)
 
case n:Int => List(1) ::: ((tri(n-1) zip tri(n-1).tail) map {case (a,b) => a+b}) ::: List(1)
for i in 0..n {
let mut c = 1;
for _j in 1..2*(n-1-i)+1 {
print!(" ");
}
for k in 0..i+1 {
print!("{:2} ", c);
c = c * (i-k)/(k+1);
}
println!();
}
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
===Functional solutions===
====Summing: Recursive row definition====
<syntaxhighlight lang="scala">
def tri(row: Int): List[Int] =
row match {
case 1 => List(1)
case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1
}</syntaxhighlight>
Function to pretty print n rows:
<syntaxhighlight lang="scala">def prettyTri(n:Int) = (1 to n) foreach {i => print(" "*(n-i)); tri(i) map (c => print(c + " ")); println}
<lang scala>
 
def prettytri(n:Int) = (1 to n) foreach {i=>print(" "*(n-i)); tri(i) map (c=>print(c+" ")); println}
prettyTri(5)</syntaxhighlight>
prettytri(5)
{{Out}}
</lang>
<pre> 1
Outputs:
1 1
<pre>
1 2 1
1 3 3 1 1
1 4 16 24 1 </pre>
====Summing: Scala Stream (Recursive & Memoization)====
1 3 3 1
<syntaxhighlight lang="scala">object Blaise extends App {
1 4 6 4 1
def pascalTriangle(): Stream[Vector[Int]] =
</pre>
Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1)
 
val output = pascalTriangle().take(15).map(_.mkString(" "))
val longest = output.last.length
 
println("Pascal's Triangle")
output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line"))
}</syntaxhighlight>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/8VqiX0P/1 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/c3dDWMCcT3eoydy6QJcWCw Scastie (JVM)].
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<langsyntaxhighlight lang="scheme">(define (next-row row)
(map + (cons 0 row) (append row '(0))))
Line 3,777 ⟶ 5,796:
 
(triangle (list 1) 5)
</syntaxhighlight>
</lang>
Output:
<syntaxhighlight lang="text">((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 3,803 ⟶ 5,822:
writeln;
end for;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func pascal(rows) {
var row = [1];
{ | n|
say row.join(' ');
row = [1, 0..(n-2).map {|i| row[i] + row[i+1] }.map(0 .. n-2)..., 1];
} *<< 1..rows;
}
 
pascal(10)</syntaxhighlight>
 
=={{header|Stata}}==
First, a few ways to compute a "Pascal matrix". With the first, the upper triangle is made of missing values (zeros with the other two).
 
<syntaxhighlight lang="stata">function pascal1(n) {
return(comb(J(1,n,0::n-1),J(n,1,0..n-1)))
}
 
function pascal2(n) {
a = I(n)
a[.,1] = J(n,1,1)
for (i=3; i<=n; i++) {
a[i,2..i-1] = a[i-1,2..i-1]+a[i-1,1..i-2]
}
return(a)
}
 
function pascal3(n) {
a = J(n,n,0)
for (i=1; i<n; i++) {
a[i+1,i] = i
}
s = p = I(n)
k = 1
for (i=0; i<n; i++) {
p = p*a/k++
s = s+p
}
return(s)
}</syntaxhighlight>
 
Now print the Pascal triangle.
 
<syntaxhighlight lang="stata">function print_pascal_triangle(n) {
a = pascal1(n)
for (i=1; i<=n; i++) {
for (j=1; j<=i; j++) {
printf("%10.0f",a[i,j])
}
printf("\n")
}
}
 
print_pascal_triangle(5)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1</syntaxhighlight>
 
pascal(10);</lang>
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func pascal(n:Int)->[Int]{
if n==1{
let a=[1]
Line 3,838 ⟶ 5,907:
}
let waste = pascal(n:10)
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
===Summing from Previous Rows===
<langsyntaxhighlight lang="tcl">proc pascal_iterative n {
if {$n < 1} {error "undefined behaviour for n < 1"}
set row [list 1]
Line 3,859 ⟶ 5,928:
}
 
puts [join [pascal_iterative 6] \n]</langsyntaxhighlight>
<pre>1
1 1
Line 3,868 ⟶ 5,937:
===Using binary coefficients===
{{trans|BASIC}}
<langsyntaxhighlight lang="tcl">proc pascal_coefficients n {
if {$n < 1} {error "undefined behaviour for n < 1"}
for {set i 0} {$i < $n} {incr i} {
Line 3,882 ⟶ 5,951:
}
 
puts [join [pascal_coefficients 6] \n]</langsyntaxhighlight>
===Combinations===
{{trans|Java}}
Thanks to Tcl 8.5's arbitrary precision integer arithmetic, this solution is not limited to a couple of dozen rows. Uses a caching factorial calculator to improve performance.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc pascal_combinations n {
Line 3,920 ⟶ 5,989:
}
 
puts [join [pascal_combinations 6] \n]</langsyntaxhighlight>
 
===Comparing Performance===
<langsyntaxhighlight lang="tcl">set n 100
puts "calculate $n rows:"
foreach proc {pascal_iterative pascal_coefficients pascal_combinations} {
puts "$proc: [time [list $proc $n] 100]"
}</langsyntaxhighlight>
{{Out}}
<pre>calculate 100 rows:
Line 3,936 ⟶ 6,005:
=={{header|TI-83 BASIC}}==
===Using Addition of Previous Rows===
<langsyntaxhighlight lang="ti83b">PROGRAM:PASCALTR
:Lbl IN
:ClrHome
Line 3,952 ⟶ 6,021:
:End
:End
:[A]</langsyntaxhighlight>
===Using nCr Function===
<langsyntaxhighlight lang="ti83b">PROGRAM:PASCALTR
:Lbl IN
:ClrHome
Line 3,966 ⟶ 6,035:
:End
:End
:[A]</langsyntaxhighlight>
 
=={{header|Turing}}==
 
<syntaxhighlight lang="turing">proc pascal (n : int)
<lang turing>
procedure pascal (n : int)
for i : 0 .. n
var c := int1
c := 1
for k : 0 .. i
put intstr(c) +: " "4 ..
c := c * (i - k) div (k + 1)
end for
Line 3,982 ⟶ 6,050:
end pascal
 
pascal(5)</langsyntaxhighlight>
 
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
 
== {{header|TypeScript}} ==
{{trans|XPL0}}
<syntaxhighlight lang="javascript">// Pascal's triangle
 
function pascal(n: number): void {
// Display the first n rows of Pascal's triangle
// if n<=0 then nothing is displayed
var ld: number[] = new Array(40); // Old
var nw: number[] = new Array(40); // New
for (var row = 0; row < n; row++) {
nw[0] = 1;
for (var i = 1; i <= row; i++)
nw[i] = ld[i - 1] + ld[i];
process.stdout.write(" ".repeat((n - row - 1) * 2));
for (var i = 0; i <= row; i++) {
if (nw[i] < 100)
process.stdout.write(" ");
process.stdout.write(nw[i].toString());
if (nw[i] < 10)
process.stdout.write(" ");
process.stdout.write(" ");
}
nw[row + 1] = 0;
// We do not copy data from nw to ld
// but we work with references.
var tmp = ld;
ld = nw;
nw = tmp;
console.log();
}
}
pascal(13);
</syntaxhighlight>
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
</pre>
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Input "Number Of Rows: "; N
@(1) = 1
Print Tab((N+1)*3);"1"
Line 3,998 ⟶ 6,125:
 
Print
End</langsyntaxhighlight>
Output:
<pre>Number Of Rows: 10
Line 4,014 ⟶ 6,141:
0 OK, 0:380
</pre>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
Any n <= 1 will print the "1" row.
<langsyntaxhighlight lang="bash">#! /bin/bash
pascal() {
local -i n=${1:-1}
Line 4,034 ⟶ 6,162:
fi
}
pascal "$1"</langsyntaxhighlight>
 
=={{header|Ursala}}==
Zero maps to the empty list. Negatives are inexpressible.
This solution uses a library function for binomial coefficients.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
pascal = choose**ziDS+ iota*t+ iota+ successor</langsyntaxhighlight>
This solution uses direct summation. The algorithm is to
insert zero at the head of a list (initially the unit list <1>), zip it with its reversal,
map the sum over the list of pairs, iterate n times, and return the trace.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
pascal "n" = (next"n" sum*NiCixp) <1></langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %nLL
 
example = pascal 10</langsyntaxhighlight>
{{Out}}
<pre><
Line 4,066 ⟶ 6,194:
<1,8,28,56,70,56,28,8,1>,
<1,9,36,84,126,126,84,36,9,1>></pre>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Option Base 1
Private Sub pascal_triangle(n As Integer)
Dim odd() As String
Dim eve() As String
ReDim odd(1)
ReDim eve(2)
odd(1) = " 1"
For i = 1 To n
If i Mod 2 = 1 Then
Debug.Print String$(2 * n - 2 * i, " ") & Join(odd, " ")
eve(1) = " 1"
ReDim Preserve eve(i + 1)
For j = 2 To i
eve(j) = Format(CStr(Val(odd(j - 1)) + Val(odd(j))), "@@@")
Next j
eve(i + 1) = " 1"
Else
Debug.Print String$(2 * n - 2 * i, " ") & Join(eve, " ")
odd(1) = " 1"
ReDim Preserve odd(i + 1)
For j = 2 To i
odd(j) = Format(CStr(Val(eve(j - 1)) + Val(eve(j))), "@@@")
Next j
odd(i + 1) = " 1"
End If
Next i
End Sub
Public Sub main()
pascal_triangle 13
End Sub</syntaxhighlight>{{out}}
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1</pre>
 
=={{header|VBScript}}==
Derived from the BASIC version.
<langsyntaxhighlight lang="vb">Pascal_Triangle(WScript.Arguments(0))
Function Pascal_Triangle(n)
Dim values(100)
Line 4,082 ⟶ 6,255:
WScript.StdOut.WriteLine
Next
End Function</langsyntaxhighlight>
{{out}}
Invoke from a command line.
Line 4,094 ⟶ 6,267:
1 5 10 10 5 1
</pre>
 
 
=={{header|Vedit macro language}}==
Line 4,104 ⟶ 6,276:
For example, if #99 contains value 2, then #@99 accesses contents of numeric register #2.
 
<langsyntaxhighlight lang="vedit">#100 = Get_Num("Number of rows: ", STATLINE)
#0=0; #1=1
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1)
Line 4,116 ⟶ 6,288:
}
Ins_Newline
}</langsyntaxhighlight>
 
===Using binary coefficients===
{{trans|BASIC}}
<langsyntaxhighlight lang="vedit">#1 = Get_Num("Number of rows: ", STATLINE)
for (#2 = 0; #2 < #1; #2++) {
#3 = 1
Line 4,129 ⟶ 6,301:
}
Ins_Newline
}</langsyntaxhighlight>
 
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
<langsyntaxhighlight lang="vb">Sub pascaltriangle()
'Pascal's triangle
Const m = 11
Line 4,151 ⟶ 6,322:
Next n
MsgBox ss, , "Pascal's triangle"
End Sub 'pascaltriangle</langsyntaxhighlight>
{{out}}
<pre>
Line 4,165 ⟶ 6,336:
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Imports System.Numerics
 
Module Module1
Iterator Function GetRow(rowNumber As BigInteger) As IEnumerable(Of BigInteger)
Dim denominator As BigInteger = 1
Dim numerator = rowNumber
 
Dim currentValue As BigInteger = 1
For counter = 0 To rowNumber
Yield currentValue
currentValue = currentValue * numerator
numerator = numerator - 1
currentValue = currentValue / denominator
denominator = denominator + 1
Next
End Function
 
Function GetTriangle(quantityOfRows As Integer) As IEnumerable(Of BigInteger())
Dim range = Enumerable.Range(0, quantityOfRows).Select(Function(num) New BigInteger(num))
Return range.Select(Function(num) GetRow(num).ToArray())
End Function
 
Function CenterString(text As String, width As Integer)
Dim spaces = width - text.Length
Dim padLeft = (spaces / 2) + text.Length
Return text.PadLeft(padLeft).PadRight(width)
End Function
 
Function FormatTriangleString(triangle As IEnumerable(Of BigInteger())) As String
Dim maxDigitWidth = triangle.Last().Max().ToString().Length
Dim rows = triangle.Select(Function(arr) String.Join(" ", arr.Select(Function(array) CenterString(array.ToString(), maxDigitWidth))))
Dim maxRowWidth = rows.Last().Length
Return String.Join(Environment.NewLine, rows.Select(Function(row) CenterString(row, maxRowWidth)))
End Function
 
Sub Main()
Dim triangle = GetTriangle(20)
Dim output = FormatTriangleString(triangle)
Console.WriteLine(output)
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
1 17 136 680 2380 6188 12376 19448 24310 24310 19448 12376 6188 2380 680 136 17 1
1 18 153 816 3060 8568 18564 31824 43758 48620 43758 31824 18564 8568 3060 816 153 18 1
1 19 171 969 3876 11628 27132 50388 75582 92378 92378 75582 50388 27132 11628 3876 969 171 19 1</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
import "./math" for Int
 
var pascalTriangle = Fn.new { |n|
if (n <= 0) return
for (i in 0...n) {
System.write(" " * (n-i-1))
for (j in 0..i) {
Fmt.write("$3d ", Int.binomial(i, j))
}
System.print()
}
}
 
pascalTriangle.call(13)</syntaxhighlight>
 
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
</pre>
 
=={{header|X86 Assembly}}==
{{works with|NASM}}
{{works with|Windows}}
<b>uses:</b> io.inc - Macro library from SASM
<syntaxhighlight lang="asm">
%include "io.inc"
 
section .text
global CMAIN
CMAIN:
mov ebx, 7 ;size
call mloop
ret
mloop:
mov edx, 0 ;edx stands for the nth line
looping:
push ebx
push edx
call line
pop edx
pop ebx
inc edx
cmp edx, ebx
jl looping
xor eax, eax
ret
line:
mov ecx, 0 ;ecx stands for the nth character in each line
mlp:
push ecx
push edx
call nCk
pop edx
pop ecx
PRINT_DEC 4, eax ;print returned number
PRINT_STRING " "
inc ecx
cmp ecx, edx ;if
jle mlp
NEWLINE
ret
nCk:
;ecx : j
;edx : i
mov esi, edx
call fac ;i!
push eax ;save i!
mov esi, ecx
call fac ;j!
push eax ;save j!
mov ebx, edx
sub ebx, ecx ;(i-j)
mov esi, ebx
call fac ;(i-j)!
pop ebx ;(i-j)! is in eax
mul ebx ;(i-j)! * j!
mov ecx, eax
pop eax ; get i!
div ecx ; ; last step : i! divided by (i-j)! * j!
ret
fac:
push ecx
push edx
mov eax, 1
mov ecx, esi
cmp ecx, 0 ; 0! returns 1
je facz
lp:
mul ecx ;multiplies eax by ecx and then decrements ecx until ecx is 0
dec ecx
cmp ecx, 0
jg lp
jmp end
facz:
mov eax, 1
end:
pop edx
pop ecx
ret
</syntaxhighlight>
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
</pre>
 
=={{header|XBasic}}==
{{trans|GW-BASIC}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">
PROGRAM "pascal"
VERSION "0.0001"
 
DECLARE FUNCTION Entry()
 
FUNCTION Entry()
r@@ = UBYTE(INLINE$("Number of rows? "))
FOR i@@ = 0 TO r@@ - 1
c%% = 1
FOR k@@ = 0 TO i@@
PRINT FORMAT$("####", c%%);
c%% = c%% * (i@@ - k@@) / (k@@ + 1)
NEXT k@@
PRINT
NEXT i@@
END FUNCTION
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Number of rows? 7
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
proc Pascal(N); \Display the first N rows of Pascal's triangle
Line 4,189 ⟶ 6,591:
];
 
Pascal(13)</langsyntaxhighlight>
 
{{Out}}
Line 4,210 ⟶ 6,612:
=={{header|zkl}}==
{{trans|C}}
<langsyntaxhighlight lang="zkl">fcn pascalTriangle(n){ // n<=0-->""
foreach i in (n){
c := 1;
Line 4,222 ⟶ 6,624:
}
pascalTriangle(8);</langsyntaxhighlight>
{{out}}
<pre>
Line 4,233 ⟶ 6,635:
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
</pre>
 
=={{header|ZX Spectrum Basic}}==
 
In edit mode insert:
<syntaxhighlight lang="basic"> 10 INPUT "How many rows? ";n
15 IF n<1 THEN GO TO 210
20 DIM c(n)
25 DIM d(n)
30 LET c(1)=1
35 LET d(1)=1
40 FOR r=1 TO n
50 FOR i=1 TO (n-r)
60 PRINT " ";
70 NEXT i
80 FOR i=1 TO r
90 PRINT c(i);" ";
100 NEXT i
110 PRINT
120 IF r>=n THEN GO TO 140
130 LET d(r+1)=1
140 FOR i=2 TO r
150 LET d(i)=c(i-1)+c(i)
160 NEXT i
165 IF r>=n THEN GO TO 200
170 FOR i=1 TO r+1
180 LET c(i)=d(i)
190 NEXT i
200 NEXT r</syntaxhighlight>
 
Then in command mode (basically don't put a number in front):
<syntaxhighlight lang="basic">RUN</syntaxhighlight>
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
</pre>
9,476

edits