Pascal's triangle: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Wren}}: Minor tidy and now uses binomial method in Math module.)
 
(29 intermediate revisions by 12 users not shown)
Line 42: Line 42:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F pascal(n)
<syntaxhighlight lang="11l">F pascal(n)
V row = [1]
V row = [1]
V k = [0]
V k = [0]
Line 49: Line 49:
row = zip(row [+] k, k [+] row).map((l, r) -> l + r)
row = zip(row [+] k, k [+] row).map((l, r) -> l + r)


pascal(7)</lang>
pascal(7)</syntaxhighlight>


{{out}}
{{out}}
Line 64: Line 64:
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
{{trans|PL/I}}
{{trans|PL/I}}
<lang 360asm>* Pascal's triangle 25/10/2015
<syntaxhighlight lang="360asm">* Pascal's triangle 25/10/2015
PASCAL CSECT
PASCAL CSECT
USING PASCAL,R15 set base register
USING PASCAL,R15 set base register
Line 101: Line 101:
XD DS CL12 temp
XD DS CL12 temp
YREGS
YREGS
END PASCAL</lang>
END PASCAL</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 119: Line 119:
=={{header|8th}}==
=={{header|8th}}==
One way, using array operations:
One way, using array operations:
<lang forth>
<syntaxhighlight lang="forth">
\ print the array
\ print the array
: .arr \ a -- a
: .arr \ a -- a
Line 135: Line 135:
\ print the first 16 rows:
\ print the first 16 rows:
[1] ' pasc 16 times
[1] ' pasc 16 times
</syntaxhighlight>
</lang>


Another way, using the relation between element 'n' and element 'n-1' in a row:
Another way, using the relation between element 'n' and element 'n-1' in a row:
<lang forth>
<syntaxhighlight lang="forth">
: ratio \ m n -- num denom
: ratio \ m n -- num denom
tuck n:- n:1+ swap ;
tuck n:- n:1+ swap ;
Line 160: Line 160:


15 pasc
15 pasc
</syntaxhighlight>
</lang>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
BYTE count=[10],row,item
BYTE count=[10],row,item
CHAR ARRAY s(5)
CHAR ARRAY s(5)
Line 180: Line 180:
PutE()
PutE()
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pascal's_triangle.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pascal's_triangle.png Screenshot from Atari 8-bit computer]
Line 200: Line 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]]
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]]


<lang ada>package Pascal is
<syntaxhighlight lang="ada">package Pascal is
type Row is array (Natural range <>) of Natural;
type Row is array (Natural range <>) of Natural;
Line 210: Line 210:
function Next_Row(R: Row) return Row;
function Next_Row(R: Row) return Row;
end Pascal;</lang>
end Pascal;</syntaxhighlight>


The implementation of that auxiliary package "Pascal":
The implementation of that auxiliary package "Pascal":


<lang Ada>package body Pascal is
<syntaxhighlight lang="ada">package body Pascal is
function First_Row(Max_Length: Positive) return Row is
function First_Row(Max_Length: Positive) return Row is
Line 239: Line 239:
end Length;
end Length;
end Pascal;</lang>
end Pascal;</syntaxhighlight>


The main program, using "Pascal". It prints the desired number of rows. The number is read from the command line.
The main program, using "Pascal". It prints the desired number of rows. The number is read from the command line.


<lang Ada>with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line, Pascal; use Pascal;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line, Pascal; use Pascal;


procedure Triangle is
procedure Triangle is
Line 260: Line 260:
Row := Next_Row(Row);
Row := Next_Row(Row);
end loop;
end loop;
end Triangle;</lang>
end Triangle;</syntaxhighlight>


{{out}}
{{out}}
Line 279: Line 279:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>PRIO MINLWB = 8, MAXUPB = 8;
<syntaxhighlight lang="algol68">PRIO MINLWB = 8, MAXUPB = 8;
OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b),
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);
MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b);
Line 297: Line 297:
# WHILE # i < stop DO
# WHILE # i < stop DO
row := row[AT 1] + row[AT 2]
row := row[AT 1] + row[AT 2]
OD</lang>
OD</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 312: Line 312:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% prints the first n lines of Pascal's triangle lines %
% prints the first n lines of Pascal's triangle lines %
% if n is <= 0, no output is produced %
% if n is <= 0, no output is produced %
Line 330: Line 330:
printPascalTriangle( 8 )
printPascalTriangle( 8 )


end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 341: Line 341:
1 6 15 20 15 6 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 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>
</pre>


Line 346: Line 387:
Pascal' s triangle of order ⍵
Pascal' s triangle of order ⍵
=== Dyalog APL ===
=== Dyalog APL ===
<lang apl>
<syntaxhighlight lang="apl">
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}
</syntaxhighlight>
</lang>


example
example


<lang apl>
<syntaxhighlight lang="apl">
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}5
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}5
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 367: Line 408:
GNU APL doesn't allow multiple statements within lambdas so the solution is phrased differently:
GNU APL doesn't allow multiple statements within lambdas so the solution is phrased differently:


<lang apl>
<syntaxhighlight lang="apl">
{{⍉⍵∘.!⍵} 0,⍳⍵}
{{⍉⍵∘.!⍵} 0,⍳⍵}
</syntaxhighlight>
</lang>


example
example


<lang apl>
<syntaxhighlight lang="apl">
{{⍉⍵∘.!⍵} 0,⍳⍵} 3
{{⍉⍵∘.!⍵} 0,⍳⍵} 3
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 386: Line 427:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
Drawing n rows from a generator:
Drawing n rows from a generator:
<lang AppleScript>-------------------- PASCAL'S TRIANGLE -------------------
<syntaxhighlight lang="applescript">-------------------- PASCAL'S TRIANGLE -------------------


-- pascal :: Generator [[Int]]
-- pascal :: Generator [[Int]]
Line 598: Line 639:
return lst
return lst
end tell
end tell
end zipWith</lang>
end zipWith</syntaxhighlight>
{{Out}}
{{Out}}
<pre> 1
<pre> 1
Line 610: Line 651:
=={{header|Arturo}}==
=={{header|Arturo}}==
{{trans|Nim}}
{{trans|Nim}}
<lang rebol>pascalTriangle: function [n][
<syntaxhighlight lang="rebol">pascalTriangle: function [n][
triangle: new [[1]]
triangle: new [[1]]


Line 622: Line 663:
loop pascalTriangle 10 'row [
loop pascalTriangle 10 'row [
print pad.center join.with: " " map to [:string] row 'x -> pad.center x 5 60
print pad.center join.with: " " map to [:string] row 'x -> pad.center x 5 60
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 639: Line 680:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?p=276617#276617 discussion]
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?p=276617#276617 discussion]
<lang AutoHotkey>n := 8, p0 := "1" ; 1+n rows of Pascal's triangle
<syntaxhighlight lang="autohotkey">n := 8, p0 := "1" ; 1+n rows of Pascal's triangle
Loop %n% {
Loop %n% {
p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1
p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1
Line 660: Line 701:


GuiClose:
GuiClose:
ExitApp</lang>
ExitApp</syntaxhighlight>


Alternate {{works with|AutoHotkey L}}
Alternate {{works with|AutoHotkey L}}
<lang AutoHotkey>Msgbox % format(pascalstriangle())
<syntaxhighlight lang="autohotkey">Msgbox % format(pascalstriangle())
Return
Return


Line 687: Line 728:
: p[row-1, col])
: p[row-1, col])
Return p
Return p
}</lang>
}</syntaxhighlight>
n <= 0 returns empty
n <= 0 returns empty


=={{header|AWK}}==
=={{header|AWK}}==
<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}}'</lang>
<syntaxhighlight 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}}'</syntaxhighlight>
{{Out}}<pre>
{{Out}}<pre>
1
1
Line 700: Line 741:
1 5 10 10 5 1
1 5 10 10 5 1
</pre>
</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}}==
=={{header|BASIC}}==
Line 714: Line 823:
If the user enters value less than 1, the first row is still always displayed.
If the user enters value less than 1, the first row is still always displayed.


<lang freebasic>DIM i AS Integer
<syntaxhighlight lang="freebasic">DIM i AS Integer
DIM row AS Integer
DIM row AS Integer
DIM nrows AS Integer
DIM nrows AS Integer
Line 729: Line 838:
NEXT i
NEXT i
PRINT
PRINT
NEXT row</lang>
NEXT row</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
Based from the Fortran Code.
Based from the Fortran Code.
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion


Line 771: Line 880:
for /l %%A in (1,1,%numspaces%) do set "space=!space! "
for /l %%A in (1,1,%numspaces%) do set "space=!space! "
goto :EOF
goto :EOF
::/The Functions.</lang>
::/The Functions.</syntaxhighlight>
{{Out}}
{{Out}}
<pre> 1
<pre> 1
Line 792: Line 901:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> nrows% = 10
<syntaxhighlight lang="bbcbasic"> nrows% = 10
colwidth% = 4
colwidth% = 4
Line 804: Line 913:
NEXT
NEXT
PRINT
PRINT
NEXT row%</lang>
NEXT row%</syntaxhighlight>
{{Out}}
{{Out}}
<pre> 1
<pre> 1
Line 818: Line 927:


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


let pascal(n) be
let pascal(n) be
Line 831: Line 940:
$)
$)
let start() be pascal(8)</lang>
let start() be pascal(8)</syntaxhighlight>
{{out}}
{{out}}
<pre> 1
<pre> 1
Line 843: Line 952:


=={{header|Befunge}}==
=={{header|Befunge}}==
<lang Befunge>0" :swor fo rebmuN">:#,_&> 55+, v
<syntaxhighlight lang="befunge">0" :swor fo rebmuN">:#,_&> 55+, v
v01*p00-1:g00.:<1p011p00:\-1_v#:<
v01*p00-1:g00.:<1p011p00:\-1_v#:<
>g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@</lang>
>g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Number of rows: 10
<pre>Number of rows: 10
Line 864: Line 973:
Displays n rows.
Displays n rows.


<lang bqn>Pascal ← {(0⊸∾+∾⟜0)⍟(↕𝕩)⋈1}
<syntaxhighlight lang="bqn">Pascal ← {(0⊸∾+∾⟜0)⍟(↕𝕩)⋈1}


•Show¨Pascal 6</lang>
•Show¨Pascal 6</syntaxhighlight>
<lang>⟨ 1 ⟩
<syntaxhighlight lang="text">⟨ 1 ⟩
⟨ 1 1 ⟩
⟨ 1 1 ⟩
⟨ 1 2 1 ⟩
⟨ 1 2 1 ⟩
⟨ 1 3 3 1 ⟩
⟨ 1 3 3 1 ⟩
⟨ 1 4 6 4 1 ⟩
⟨ 1 4 6 4 1 ⟩
⟨ 1 5 10 10 5 1 ⟩</lang>
⟨ 1 5 10 10 5 1 ⟩</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( out$"Number of rows? "
<syntaxhighlight lang="bracmat">( out$"Number of rows? "
& get':?R
& get':?R
& -1:?I
& -1:?I
Line 892: Line 1,001:
)
)
&
&
)</lang>
)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Number of rows?
<pre>Number of rows?
Line 906: Line 1,015:
=={{header|Burlesque}}==
=={{header|Burlesque}}==


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S
blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S
1
1
Line 925: Line 1,034:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 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 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Line 931: Line 1,040:
{{trans|Fortran}}
{{trans|Fortran}}


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


void pascaltriangle(unsigned int n)
void pascaltriangle(unsigned int n)
Line 952: Line 1,061:
pascaltriangle(8);
pascaltriangle(8);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


===Recursive===
===Recursive===
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


#define D 32
#define D 32
Line 972: Line 1,081:
int x[D] = {0, 1, 0}, y[D] = {0};
int x[D] = {0, 1, 0}, y[D] = {0};
return pascals(x, y, 0);
return pascals(x, y, 0);
}</lang>
}</syntaxhighlight>


===Adding previous row values===
===Adding previous row values===


<lang c>void triangleC(int nRows) {
<syntaxhighlight lang="c">void triangleC(int nRows) {
if (nRows <= 0) return;
if (nRows <= 0) return;
int *prevRow = NULL;
int *prevRow = NULL;
Line 991: Line 1,100:
}
}
free(prevRow);
free(prevRow);
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 997: Line 1,106:
Produces no output when n is less than or equal to zero.
Produces no output when n is less than or equal to zero.


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


namespace RosettaCode {
namespace RosettaCode {
Line 1,021: Line 1,130:
}
}
}
}
}</lang>
}</syntaxhighlight>


===Arbitrarily large numbers (BigInteger), arbitrary row selection===
===Arbitrarily large numbers (BigInteger), arbitrary row selection===
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;
using System.Numerics;
using System.Numerics;
Line 1,071: Line 1,180:
}
}
}
}
}</lang>
}</syntaxhighlight>


Example:
Example:
<lang csharp>static void Main()
<syntaxhighlight lang="csharp">static void Main()
{
{
IEnumerable<BigInteger[]> triangle = PascalsTriangle.GetTriangle(20);
IEnumerable<BigInteger[]> triangle = PascalsTriangle.GetTriangle(20);
string output = PascalsTriangle.FormatTriangleString(triangle)
string output = PascalsTriangle.FormatTriangleString(triangle)
Console.WriteLine(output);
Console.WriteLine(output);
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,106: Line 1,215:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <algorithm>
#include <algorithm>
#include<cstdio>
#include<cstdio>
Line 1,185: Line 1,294:
}
}


}</lang>
}</syntaxhighlight>
===C++11 (with dynamic and semi-static vectors)===
===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.
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.
<lang cpp>// Compile with -std=c++11
<syntaxhighlight lang="cpp">// Compile with -std=c++11
#include<iostream>
#include<iostream>
#include<vector>
#include<vector>
Line 1,274: Line 1,383:
}
}


</syntaxhighlight>
</lang>
===C++11 (with a class) ===
===C++11 (with a class) ===
A full fledged example with a class definition and methods to retrieve data, worthy of the title object-oriented.
A full fledged example with a class definition and methods to retrieve data, worthy of the title object-oriented.
<lang cpp>// Compile with -std=c++11
<syntaxhighlight lang="cpp">// Compile with -std=c++11
#include<iostream>
#include<iostream>
#include<vector>
#include<vector>
Line 1,358: Line 1,467:
}
}


</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{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).
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).
<lang lisp>(defn pascal [n]
<syntaxhighlight lang="lisp">(defn pascal [n]
(let [newrow (fn newrow [lst ret]
(let [newrow (fn newrow [lst ret]
(if lst
(if lst
Line 1,374: Line 1,483:
(recur (dec n) (conj (newrow lst []) 1)))))]
(recur (dec n) (conj (newrow lst []) 1)))))]
(genrow n [1])))
(genrow n [1])))
(pascal 4)</lang>
(pascal 4)</syntaxhighlight>
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:
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:
<lang lisp>
<syntaxhighlight lang="lisp">
(defn nextrow [row]
(defn nextrow [row]
(vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] )))
(vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] )))
Line 1,385: Line 1,494:
(doseq [row triangle]
(doseq [row triangle]
(println row))))
(println row))))
</syntaxhighlight>
</lang>
The ''assert'' form causes the ''pascal'' function to throw an exception unless the argument is (integral and) positive.
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
Here's a third version using the ''iterate'' function
<lang lisp>
<syntaxhighlight lang="lisp">
(def pascal
(def pascal
(iterate
(iterate
Line 1,397: Line 1,506:
(map (partial apply +) ,,,)))
(map (partial apply +) ,,,)))
[1]))
[1]))
</syntaxhighlight>
</lang>


Another short version which returns an infinite pascal triangle as a list, using the iterate function.
Another short version which returns an infinite pascal triangle as a list, using the iterate function.


<lang lisp>
<syntaxhighlight lang="lisp">
(def pascal
(def pascal
(iterate #(concat [1]
(iterate #(concat [1]
Line 1,407: Line 1,516:
[1])
[1])
[1]))
[1]))
</syntaxhighlight>
</lang>


One can then get the first n rows using the take function
One can then get the first n rows using the take function


<lang lisp>
<syntaxhighlight lang="lisp">
(take 10 pascal) ; returns a list of the first 10 pascal rows
(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
Also, one can retrieve the nth row using the nth function


<lang lisp>
<syntaxhighlight lang="lisp">
(nth pascal 10) ;returns the nth row
(nth pascal 10) ;returns the nth row
</syntaxhighlight>
</lang>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
This version assumes n is an integer and n >= 1. It efficiently computes binomial coefficients.
This version assumes n is an integer and n >= 1. It efficiently computes binomial coefficients.
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
pascal = (n) ->
pascal = (n) ->
width = 6
width = 6
Line 1,453: Line 1,562:
pascal(7)
pascal(7)


</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 1,468: Line 1,577:


=={{header|Commodore BASIC}}==
=={{header|Commodore BASIC}}==
<lang BASIC>10 INPUT "HOW MANY";N
<syntaxhighlight lang="basic">10 INPUT "HOW MANY";N
20 IF N<1 THEN END
20 IF N<1 THEN END
30 DIM C(N)
30 DIM C(N)
Line 1,491: Line 1,600:
220 C(I)=D(I)
220 C(I)=D(I)
230 NEXT I
230 NEXT I
240 NEXT J</lang>
240 NEXT J</syntaxhighlight>


Output:
Output:
<lang>RUN
<syntaxhighlight lang="text">RUN
HOW MANY? 8
HOW MANY? 8
1
1
Line 1,506: Line 1,615:
1 8 28 56 70 56 28 8 1
1 8 28 56 70 56 28 8 1
READY.
READY.
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
To evaluate, call (pascal n). For n < 1, it simply returns nil.
To evaluate, call (pascal n). For n < 1, it simply returns nil.


<lang lisp>(defun pascal (n)
<syntaxhighlight lang="lisp">(defun pascal (n)
(genrow n '(1)))
(genrow n '(1)))


(defun genrow (n l)
(defun genrow (n l)
(when (< 0 n)
(when (plusp n)
(print l)
(print l)
(genrow (1- n) (cons 1 (newrow l)))))
(genrow (1- n) (cons 1 (newrow l)))))


(defun newrow (l)
(defun newrow (l)
(if (> 2 (length l))
(if (null (rest l))
'(1)
'(1)
(cons (+ (car l) (cadr l)) (newrow (cdr l)))))</lang>
(cons (+ (first l) (second l))
(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))''.
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))''.


<lang lisp>(defun pascal-next-row (a)
<syntaxhighlight lang="lisp">(defun pascal-next-row (a)
(loop :for q :in a
(loop :for q :in a
:and p = 0 :then q
:and p = 0 :then q
:as s = (list (+ p q))
:as s = (list (+ p q))
:nconc s :into a
:nconc s :into a
:finally (rplacd s (list 1))
:finally (rplacd s (list 1))
(return a)))
(return a)))


(defun pascal (n)
(defun pascal (n)
(loop :for a = (list 1) :then (pascal-next-row a)
(loop :for a = (list 1) :then (pascal-next-row a)
:repeat n
:repeat n
:collect a))</lang>
:collect a))</syntaxhighlight>


Another iterative solution, this time using pretty-printing to automatically print the triangle in the shape of a triangle in the terminal. The pascal-print function determines the length of the final row and uses it to decide how wide the triangle should be.
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.


<lang lisp>
<syntaxhighlight lang="lisp">
(defun next-pascal (l)
(defun next-pascal-triangle-row (list)
`(1
`(1 ,@(loop for i from 0 to (- (length l) 2)
collect (+ (nth i l) (nth (1+ i) l)))
,.(mapcar #'+ list (rest list))
1))
1))


(defun pascal-print (r)
(defun pascal-triangle (number-of-rows)
(loop repeat number-of-rows
(let* ((pasc (loop with p = (list (list 1))
repeat r do (nconc p (list (apply #'next-pascal (last p))))
for row = '(1) then (next-pascal-triangle-row row)
finally (return p)))
collect row))

(len (length (format nil "~A" (car (last pasc))))))
(defun print-pascal-triangle (number-of-rows)
(format t (format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" len) pasc)))
(let* ((triangle (pascal-triangle number-of-rows))
</lang>
(max-row-length (length (write-to-string (first (last triangle))))))
(format t
(format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" max-row-length)
triangle)))
</syntaxhighlight>


For example:
For example:


<lang lisp>(pascal-print 4)</lang>
<syntaxhighlight lang="lisp">(print-pascal-triangle 4)</syntaxhighlight>
<lang>
<syntaxhighlight lang="text">
1
1
1 1
1 1
1 2 1
1 2 1
1 3 3 1
1 3 3 1
</syntaxhighlight>
1 4 6 4 1
<syntaxhighlight lang="lisp">(print-pascal-triangle 8)</syntaxhighlight>
</lang>
<syntaxhighlight lang="text">
<lang lisp>(pascal-print 8)</lang>
1
<lang>
1
1 1
1 1
1 2 1
1 2 1
1 3 3 1
1 3 3 1
1 4 6 4 1
1 4 6 4 1
1 5 10 10 5 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
</syntaxhighlight>
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
</lang>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
{{Works with|BlackBox Component Builder}}
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE PascalTriangle;
MODULE PascalTriangle;
IMPORT StdLog, DevCommanders, TextMappers;
IMPORT StdLog, DevCommanders, TextMappers;
Line 1,652: Line 1,765:


END PascalTriangle.
END PascalTriangle.
</syntaxhighlight>
</lang>
<pre>Execute: ^Q PascalTriangle.Do 0 1 2 3 4 5 6 7 8 9 10 11 12~</pre>
<pre>Execute: ^Q PascalTriangle.Do 0 1 2 3 4 5 6 7 8 9 10 11 12~</pre>
{{out}}
{{out}}
Line 1,673: Line 1,786:
=={{header|D}}==
=={{header|D}}==
===Less functional Version===
===Less functional Version===
<lang d>int[][] pascalsTriangle(in int rows) pure nothrow {
<syntaxhighlight lang="d">int[][] pascalsTriangle(in int rows) pure nothrow {
auto tri = new int[][rows];
auto tri = new int[][rows];
foreach (r; 0 .. rows) {
foreach (r; 0 .. rows) {
Line 1,697: Line 1,810:
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]);
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]);
}</lang>
}</syntaxhighlight>
===More functional Version===
===More functional Version===
<lang d>import std.stdio, std.algorithm, std.range;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;


auto pascal() pure nothrow {
auto pascal() pure nothrow {
Line 1,709: Line 1,822:
void main() {
void main() {
pascal.take(5).writeln;
pascal.take(5).writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]</pre>
<pre>[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]</pre>
Line 1,717: Line 1,830:
Their difference are the initial line and the operation that act on the line element to produce next line.
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).
The following is a generic pascal's triangle implementation for positive number of lines output (n).
<lang d>import std.stdio, std.string, std.array, std.format;
<syntaxhighlight lang="d">import std.stdio, std.string, std.array, std.format;


string Pascal(alias dg, T, T initValue)(int n) {
string Pascal(alias dg, T, T initValue)(int n) {
Line 1,758: Line 1,871:
foreach (i; [16])
foreach (i; [16])
writef(sierpinski(i));
writef(sierpinski(i));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 1
<pre> 1
Line 1,793: Line 1,906:


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>
<syntaxhighlight lang="dart">
import 'dart:io';
import 'dart:io';


Line 1,836: Line 1,949:




</syntaxhighlight>
</lang>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang delphi>program PascalsTriangle;
<syntaxhighlight lang="delphi">program PascalsTriangle;


procedure Pascal(r:Integer);
procedure Pascal(r:Integer);
Line 1,859: Line 1,972:
begin
begin
Pascal(9);
Pascal(9);
end.</lang>
end.</syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==
Doesn't print anything for negative or null values.
Doesn't print anything for negative or null values.
<lang delphi>procedure Pascal(r : Integer);
<syntaxhighlight lang="delphi">procedure Pascal(r : Integer);
var
var
i, c, k : Integer;
i, c, k : Integer;
Line 1,877: Line 1,990:
end;
end;


Pascal(9);</lang>
Pascal(9);</syntaxhighlight>
{{Out}}
{{Out}}
<pre> 1
<pre> 1
Line 1,893: Line 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.
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.


<lang e>def pascalsTriangle(n, out) {
<syntaxhighlight lang="e">def pascalsTriangle(n, out) {
def row := [].diverge(int)
def row := [].diverge(int)
out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>")
out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>")
Line 1,912: Line 2,025:
}
}
out.print("</table>")
out.print("</table>")
}</lang>
}</syntaxhighlight>


<lang e>def out := <file:triangle.html>.textWriter()
<syntaxhighlight lang="e">def out := <file:triangle.html>.textWriter()
try {
try {
pascalsTriangle(15, out)
pascalsTriangle(15, out)
Line 1,920: Line 2,033:
out.close()
out.close()
}
}
makeCommand("yourFavoriteWebBrowser")("triangle.html")</lang>
makeCommand("yourFavoriteWebBrowser")("triangle.html")</syntaxhighlight>

=={{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}}==
=={{header|Eiffel}}==


<lang eiffel>
<syntaxhighlight lang="eiffel">
note
note
description : "Prints pascal's triangle"
description : "Prints pascal's triangle"
Line 2,026: Line 2,163:
--Contains all already calculated lines
--Contains all already calculated lines
end
end
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Pascal do
<syntaxhighlight lang="elixir">defmodule Pascal do
def triangle(n), do: triangle(n,[1])
def triangle(n), do: triangle(n,[1])
Line 2,040: Line 2,177:
end
end


Pascal.triangle(8)</lang>
Pascal.triangle(8)</syntaxhighlight>


{{out}}
{{out}}
Line 2,056: Line 2,193:
=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
===Using mapcar and append, returing a list of rows===
===Using mapcar and append, returing a list of rows===
<lang lisp>(require 'cl-lib)
<syntaxhighlight lang="lisp">(require 'cl-lib)


(defun next-row (row)
(defun next-row (row)
Line 2,065: Line 2,202:
(if (= rows 0)
(if (= rows 0)
'()
'()
(cons row (triangle (next-row row) (- rows 1)))))</lang>
(cons row (triangle (next-row row) (- rows 1)))))</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,079: Line 2,216:
</pre>
</pre>
===Translation from Pascal===
===Translation from Pascal===
<lang lisp>(defun pascal (r)
<syntaxhighlight lang="lisp">(defun pascal (r)
(dotimes (i r)
(dotimes (i r)
(let ((c 1))
(let ((c 1))
Line 2,086: Line 2,223:
(setq c (/ (* c (- i k))
(setq c (/ (* c (- i k))
(+ k 1))))
(+ k 1))))
(terpri))))</lang>
(terpri))))</syntaxhighlight>
{{Out}}
{{Out}}
From the REPL:
From the REPL:
Line 2,100: Line 2,237:
===Returning a string===
===Returning a string===
Same as the translation from Pascal, but now returning a string.
Same as the translation from Pascal, but now returning a string.
<lang lisp>(defun pascal (r)
<syntaxhighlight lang="lisp">(defun pascal (r)
(let ((out ""))
(let ((out ""))
(dotimes (i r)
(dotimes (i r)
Line 2,109: Line 2,246:
(+ k 1))))
(+ k 1))))
(setq out (concat out "\n"))))
(setq out (concat out "\n"))))
out))</lang>
out))</syntaxhighlight>
{{Out}}
{{Out}}
Now, since this one returns a string, it is possible to insert the result in the current buffer:
Now, since this one returns a string, it is possible to insert the result in the current buffer:
Line 2,125: Line 2,262:
=={{header|Erlang}}==
=={{header|Erlang}}==


<lang erlang>
<syntaxhighlight lang="erlang">
-import(lists).
-import(lists).
-export([pascal/1]).
-export([pascal/1]).
Line 2,134: Line 2,271:
[H|_] = L,
[H|_] = L,
[lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].
[lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 2,144: Line 2,281:


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM PASCAL_TRIANGLE
PROGRAM PASCAL_TRIANGLE


Line 2,162: Line 2,299:
PASCAL(9)
PASCAL(9)
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,178: Line 2,315:
=={{header|Euphoria}}==
=={{header|Euphoria}}==
===Summing from Previous Rows===
===Summing from Previous Rows===
<lang Euphoria>sequence row
<syntaxhighlight lang="euphoria">sequence row
row = {}
row = {}
for m = 1 to 10 do
for m = 1 to 10 do
Line 2,187: Line 2,324:
print(1,row)
print(1,row)
puts(1,'\n')
puts(1,'\n')
end for</lang>
end for</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,211: Line 2,348:


{{Works with|Office 365 betas 2021}}
{{Works with|Office 365 betas 2021}}
<lang lisp>PASCAL
<syntaxhighlight lang="lisp">PASCAL
=LAMBDA(n,
=LAMBDA(n,
BINCOEFF(n - 1)(
BINCOEFF(n - 1)(
Line 2,224: Line 2,361:
QUOTIENT(FACT(n), FACT(k) * FACT(n - k))
QUOTIENT(FACT(n), FACT(k) * FACT(n - k))
)
)
)</lang>
)</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,382: Line 2,519:
Or defining the whole triangle as a single grid, by binding the name TRIANGLE to an additional lambda:
Or defining the whole triangle as a single grid, by binding the name TRIANGLE to an additional lambda:


<lang lisp>TRIANGLE
<syntaxhighlight lang="lisp">TRIANGLE
=LAMBDA(n,
=LAMBDA(n,
LET(
LET(
Line 2,393: Line 2,530:
)
)
)
)
)</lang>
)</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,550: Line 2,687:


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>let rec nextrow l =
<syntaxhighlight lang="fsharp">let rec nextrow l =
match l with
match l with
| [] -> []
| [] -> []
Line 2,562: Line 2,699:
printf "%s" (i.ToString() + ", ")
printf "%s" (i.ToString() + ", ")
printfn "%s" "\n"
printfn "%s" "\n"
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
Line 2,568: Line 2,705:
This implementation works by summing the previous line content. Result for n < 1 is the same as for n == 1.
This implementation works by summing the previous line content. Result for n < 1 is the same as for n == 1.


<lang factor>USING: grouping kernel math sequences ;
<syntaxhighlight lang="factor">USING: grouping kernel math sequences ;


: (pascal) ( seq -- newseq )
: (pascal) ( seq -- newseq )
Line 2,574: Line 2,711:


: pascal ( n -- seq )
: pascal ( n -- seq )
1 - { { 1 } } swap [ (pascal) ] times ;</lang>
1 - { { 1 } } swap [ (pascal) ] times ;</syntaxhighlight>


It works as:
It works as:


<lang factor>5 pascal .
<syntaxhighlight lang="factor">5 pascal .
{ { 1 } { 1 1 } { 1 2 1 } { 1 3 3 1 } { 1 4 6 4 1 } }</lang>
{ { 1 } { 1 1 } { 1 2 1 } { 1 3 3 1 } { 1 4 6 4 1 } }</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 2,613: Line 2,750:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|FOCAL}}==
=={{header|FOCAL}}==
<lang FOCAL>1.1 S OLD(1)=1; T %4.0, 1, !
<syntaxhighlight lang="focal">1.1 S OLD(1)=1; T %4.0, 1, !
1.2 F N=1,10; D 2
1.2 F N=1,10; D 2
1.3 Q
1.3 Q
Line 2,626: Line 2,763:


3.1 S OLD(X)=NEW(X)
3.1 S OLD(X)=NEW(X)
3.2 T %4.0, OLD(X)</lang>
3.2 T %4.0, OLD(X)</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 2,643: Line 2,780:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: init ( n -- )
<syntaxhighlight lang="forth">: init ( n -- )
here swap cells erase 1 here ! ;
here swap cells erase 1 here ! ;
: .line ( n -- )
: .line ( n -- )
Line 2,653: Line 2,790:
: pascal ( n -- )
: pascal ( n -- )
dup init 1 .line
dup init 1 .line
1 ?do i next i 1+ .line loop ;</lang>
1 ?do i next i 1+ .line loop ;</syntaxhighlight>
This is a bit more efficient.
This is a bit more efficient.
{{trans|C}}
{{trans|C}}
<lang forth>: PascTriangle
<syntaxhighlight lang="forth">: PascTriangle
cr dup 0
cr dup 0
?do
?do
Line 2,663: Line 2,800:
;
;


13 PascTriangle</lang>
13 PascTriangle</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
Prints nothing for n<=0. Output formatting breaks down for n>20
Prints nothing for n<=0. Output formatting breaks down for n>20
<lang fortran>PROGRAM Pascals_Triangle
<syntaxhighlight lang="fortran">PROGRAM Pascals_Triangle


CALL Print_Triangle(8)
CALL Print_Triangle(8)
Line 2,693: Line 2,830:
END DO
END DO


END SUBROUTINE Print_Triangle</lang>
END SUBROUTINE Print_Triangle</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Sub pascalTriangle(n As UInteger)
Sub pascalTriangle(n As UInteger)
Line 2,732: Line 2,869:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 2,754: Line 2,891:
=={{header|Frink}}==
=={{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.
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.
<lang frink>
<syntaxhighlight lang="frink">
pascal[rows] :=
pascal[rows] :=
{
{
Line 2,770: Line 2,907:


pascal[10]
pascal[10]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,789: Line 2,926:
=== Summing from Previous Rows ===
=== Summing from Previous Rows ===
{{trans|Scala}}
{{trans|Scala}}
<lang funl>import lists.zip
<syntaxhighlight lang="funl">import lists.zip


def
def
pascal( 1 ) = [1]
pascal( 1 ) = [1]
pascal( n ) = [1] + map( (a, b) -> a + b, zip(pascal(n-1), pascal(n-1).tail()) ) + [1]</lang>
pascal( n ) = [1] + map( (a, b) -> a + b, zip(pascal(n-1), pascal(n-1).tail()) ) + [1]</syntaxhighlight>


=== Combinations ===
=== Combinations ===
{{trans|Haskell}}
{{trans|Haskell}}
<lang funl>import integers.choose
<syntaxhighlight lang="funl">import integers.choose


def pascal( n ) = [choose( n - 1, k ) | k <- 0..n-1]</lang>
def pascal( n ) = [choose( n - 1, k ) | k <- 0..n-1]</syntaxhighlight>


=== Pascal's Triangle ===
=== Pascal's Triangle ===
<lang funl>def triangle( height ) =
<syntaxhighlight lang="funl">def triangle( height ) =
width = max( map(a -> a.toString().length(), pascal(height)) )
width = max( map(a -> a.toString().length(), pascal(height)) )


Line 2,812: Line 2,949:
println( map(a -> format('%' + width + 'd ', a), pascal(n)).mkString() )
println( map(a -> format('%' + width + 'd ', a), pascal(n)).mkString() )


triangle( 10 )</lang>
triangle( 10 )</syntaxhighlight>


{{out}}
{{out}}
Line 2,830: Line 2,967:
=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==


{{FormulaeEntry|page=https://formulae.org/?script=examples/Pascal%27s_triangle}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.


'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.


[[File:Fōrmulæ - Pascal's triangle 01.png]]
In '''[https://formulae.org/?example=Pascal%27s_triangle this]''' page you can see the program(s) related to this task and their results.

'''Test case'''

[[File:Fōrmulæ - Pascal's triangle 02.png]]

[[File:Fōrmulæ - Pascal's triangle 03.png]]


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>Pascal := function(n)
<syntaxhighlight lang="gap">Pascal := function(n)
local i, v;
local i, v;
v := [1];
v := [1];
Line 2,855: Line 2,998:
# [ 1, 6, 15, 20, 15, 6, 1 ]
# [ 1, 6, 15, 20, 15, 6, 1 ]
# [ 1, 7, 21, 35, 35, 21, 7, 1 ]
# [ 1, 7, 21, 35, 35, 21, 7, 1 ]
# [ 1, 8, 28, 56, 70, 56, 28, 8, 1 ]</lang>
# [ 1, 8, 28, 56, 70, 56, 28, 8, 1 ]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
No output for n < 1. Otherwise, output formatted left justified.
No output for n < 1. Otherwise, output formatted left justified.
<syntaxhighlight lang="go">
<lang go>
package main
package main


Line 2,902: Line 3,045:
printTriangle(4)
printTriangle(4)
}
}
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,914: Line 3,057:
=== Recursive ===
=== Recursive ===
In the spirit of the Haskell "think in whole lists" solution here is a list-driven, minimalist solution:
In the spirit of the Haskell "think in whole lists" solution here is a list-driven, minimalist solution:
<lang groovy>def pascal
<syntaxhighlight lang="groovy">def pascal
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }</lang>
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }</syntaxhighlight>
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.
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:
Test program:
<lang groovy>def count = 15
<syntaxhighlight lang="groovy">def count = 15
(1..count).each { n ->
(1..count).each { n ->
printf ("%2d:", n); (0..(count-n)).each { print " " }; pascal(n).each{ printf("%6d ", it) }; println ""
printf ("%2d:", n); (0..(count-n)).each { print " " }; pascal(n).each{ printf("%6d ", it) }; println ""
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,942: Line 3,085:


=={{header|GW-BASIC}}==
=={{header|GW-BASIC}}==
<lang qbasic>10 INPUT "Number of rows? ",R
<syntaxhighlight lang="qbasic">10 INPUT "Number of rows? ",R
20 FOR I=0 TO R-1
20 FOR I=0 TO R-1
30 C=1
30 C=1
Line 2,950: Line 3,093:
70 NEXT
70 NEXT
80 PRINT
80 PRINT
90 NEXT</lang>
90 NEXT</syntaxhighlight>


Output:
Output:
Line 2,972: Line 3,115:
similar function
similar function


<lang haskell>zapWith :: (a -> a -> a) -> [a] -> [a] -> [a]
<syntaxhighlight lang="haskell">zapWith :: (a -> a -> a) -> [a] -> [a] -> [a]
zapWith f xs [] = xs
zapWith f xs [] = xs
zapWith f [] ys = ys
zapWith f [] ys = ys
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys</lang>
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys</syntaxhighlight>


Now we can shift a list and add it to itself, extending it by keeping
Now we can shift a list and add it to itself, extending it by keeping
the ends:
the ends:


<lang haskell>extendWith f [] = []
<syntaxhighlight lang="haskell">extendWith f [] = []
extendWith f xs@(x:ys) = x : zapWith f xs ys</lang>
extendWith f xs@(x:ys) = x : zapWith f xs ys</syntaxhighlight>


And for the whole (infinite) triangle, we just iterate this operation,
And for the whole (infinite) triangle, we just iterate this operation,
starting with the first row:
starting with the first row:


<lang haskell>pascal = iterate (extendWith (+)) [1]</lang>
<syntaxhighlight lang="haskell">pascal = iterate (extendWith (+)) [1]</syntaxhighlight>


For the first ''n'' rows, we just take the first ''n'' elements from this
For the first ''n'' rows, we just take the first ''n'' elements from this
list, as in
list, as in


<lang haskell>*Main> take 6 pascal
<syntaxhighlight 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]]</lang>
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]</syntaxhighlight>


A shorter approach, plagiarized from [http://www.haskell.org/haskellwiki/Blow_your_mind]
A shorter approach, plagiarized from [http://www.haskell.org/haskellwiki/Blow_your_mind]
<lang haskell>-- generate next row from current row
<syntaxhighlight lang="haskell">-- generate next row from current row
nextRow row = zipWith (+) ([0] ++ row) (row ++ [0])
nextRow row = zipWith (+) ([0] ++ row) (row ++ [0])


-- returns the first n rows
-- returns the first n rows
pascal = iterate nextRow [1]</lang>
pascal = iterate nextRow [1]</syntaxhighlight>


Alternatively, using list comprehensions:
Alternatively, using list comprehensions:


<lang haskell>
<syntaxhighlight lang="haskell">
pascal :: [[Integer]]
pascal :: [[Integer]]
pascal =
pascal =
(1 : [ 0 | _ <- head pascal])
(1 : [ 0 | _ <- head pascal])
: [zipWith (+) (0:row) row | row <- pascal]
: [zipWith (+) (0:row) row | row <- pascal]
</syntaxhighlight>
</lang>


<lang haskell>
<syntaxhighlight lang="haskell">
*Pascal> take 5 <$> (take 5 $ triangle)
*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]]
[[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>
</lang>


With binomial coefficients:
With binomial coefficients:
<lang haskell>fac = product . enumFromTo 1
<syntaxhighlight lang="haskell">fac = product . enumFromTo 1


binCoef n k = fac n `div` (fac k * fac (n - k))
binCoef n k = fac n `div` (fac k * fac (n - k))


pascal = ((fmap . binCoef) <*> enumFromTo 0) . pred</lang>
pascal = ((fmap . binCoef) <*> enumFromTo 0) . pred</syntaxhighlight>


Example:
Example:
<lang haskell>*Main> putStr $ unlines $ map unwords $ map (map show) $ pascal 10
<syntaxhighlight lang="haskell">*Main> putStr $ unlines $ map unwords $ map (map show) $ pascal 10
1
1
1 1
1 1
Line 3,034: Line 3,177:
1 8 28 56 70 56 28 8 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 9 36 84 126 126 84 36 9 1
</syntaxhighlight>
</lang>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst> CALL Pascal(30)
<syntaxhighlight lang="hicest"> CALL Pascal(30)


SUBROUTINE Pascal(rows)
SUBROUTINE Pascal(rows)
Line 3,051: Line 3,194:
ENDDO
ENDDO
ENDDO
ENDDO
END</lang>
END</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{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.
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.
It also presents the data as an isoceles triangle.
<lang Icon>link math
<syntaxhighlight lang="icon">link math
procedure main(A)
procedure main(A)
Line 3,075: Line 3,218:
write()
write()
}
}
end</lang>
end</syntaxhighlight>


{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
Line 3,101: Line 3,244:


=={{header|IDL}}==
=={{header|IDL}}==
<lang IDL>Pro Pascal, n
<syntaxhighlight lang="idl">Pro Pascal, n
;n is the number of lines of the triangle to be displayed
;n is the number of lines of the triangle to be displayed
r=[1]
r=[1]
Line 3,117: Line 3,260:
print, r
print, r


End</lang>
End</syntaxhighlight>


=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 PROGRAM "PascalTr.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "PascalTr.bas"
110 TEXT 80
110 TEXT 80
120 LET ROW=12
120 LET ROW=12
Line 3,131: Line 3,274:
190 NEXT
190 NEXT
200 PRINT
200 PRINT
210 NEXT</lang>
210 NEXT</syntaxhighlight>


{{out}}
{{out}}
Line 3,149: Line 3,292:


=={{header|ivy}}==
=={{header|ivy}}==
<lang ivy>
<syntaxhighlight lang="ivy">
op pascal N = transp (0 , iota N) o.! -1 , iota N
op pascal N = transp (0 , iota N) o.! -1 , iota N
pascal 5
pascal 5
Line 3,158: Line 3,301:
1 4 6 4 1 0
1 4 6 4 1 0
1 5 10 10 5 1
1 5 10 10 5 1
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==
<lang j> !~/~ i.5
<syntaxhighlight lang="j"> !~/~ i.5
1 0 0 0 0
1 0 0 0 0
1 1 0 0 0
1 1 0 0 0
1 2 1 0 0
1 2 1 0 0
1 3 3 1 0
1 3 3 1 0
1 4 6 4 1</lang>
1 4 6 4 1</syntaxhighlight>


<lang j> ([: ":@-.&0"1 !~/~)@i. 5
<syntaxhighlight lang="j"> ([: ":@-.&0"1 !~/~)@i. 5
1
1
1 1
1 1
1 2 1
1 2 1
1 3 3 1
1 3 3 1
1 4 6 4 1</lang>
1 4 6 4 1</syntaxhighlight>


<lang j> (-@|. |."_1 [: ":@-.&0"1 !~/~)@i. 5
<syntaxhighlight lang="j"> (-@|. |."_1 [: ":@-.&0"1 !~/~)@i. 5
1
1
1 1
1 1
1 2 1
1 2 1
1 3 3 1
1 3 3 1
1 4 6 4 1</lang>
1 4 6 4 1</syntaxhighlight>

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
See the [[Talk:Pascal's_triangle#J_Explanation|talk page]] for explanation of earlier version
Line 3,189: Line 3,378:
===Summing from Previous Rows===
===Summing from Previous Rows===
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java>import java.util.ArrayList;
<syntaxhighlight lang="java">import java.util.ArrayList;
...//class definition, etc.
...//class definition, etc.
public static void genPyrN(int rows){
public static void genPyrN(int rows){
Line 3,209: Line 3,398:
System.out.println(thisRow);
System.out.println(thisRow);
}
}
}</lang>
}</syntaxhighlight>


===Combinations===
===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.
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.
<lang java>public class Pas{
<syntaxhighlight lang="java">public class Pas{
public static void main(String[] args){
public static void main(String[] args){
//usage
//usage
Line 3,239: Line 3,428:
return ans;
return ans;
}
}
}</lang>
}</syntaxhighlight>


===Using arithmetic calculation of each row element ===
===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.
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.
<lang java>
<syntaxhighlight lang="java">
public class Pascal {
public class Pascal {
private static void printPascalLine (int n) {
private static void printPascalLine (int n) {
Line 3,263: Line 3,452:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 3,270: Line 3,459:
{{works with|SpiderMonkey}}
{{works with|SpiderMonkey}}
{{works with|V8}}
{{works with|V8}}
<lang javascript>// Pascal's triangle object
<syntaxhighlight lang="javascript">// Pascal's triangle object
function pascalTriangle (rows) {
function pascalTriangle (rows) {


Line 3,340: Line 3,529:
// Display 8 row triangle in base 16
// Display 8 row triangle in base 16
tri = new pascalTriangle(8);
tri = new pascalTriangle(8);
tri.print(16);</lang>
tri.print(16);</syntaxhighlight>
Output:
Output:
<pre>$ d8 pascal.js
<pre>$ d8 pascal.js
Line 3,358: Line 3,547:
====Functional====
====Functional====
{{Trans|Haskell}}
{{Trans|Haskell}}
<lang JavaScript>(function (n) {
<syntaxhighlight lang="javascript">(function (n) {
'use strict';
'use strict';


Line 3,459: Line 3,648:
}), false, 'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
}), false, 'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n');
'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n');
})(7);</lang>
})(7);</syntaxhighlight>
{{Out}}
{{Out}}
{| class="wikitable" style="text-align:center;width:26em;height:26em;table-layout:fixed;"
{| class="wikitable" style="text-align:center;width:26em;height:26em;table-layout:fixed;"
Line 3,478: Line 3,667:
|}
|}


<lang 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]]</lang>
<syntaxhighlight lang="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]]</syntaxhighlight>


===ES6===
===ES6===
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 3,589: Line 3,778:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre> 1
<pre> 1
Line 3,603: Line 3,792:


====Recursive====
====Recursive====
<lang javascript>
<syntaxhighlight lang="javascript">
const aux = n => {
const aux = n => {
if(n <= 1) return [1]
if(n <= 1) return [1]
Line 3,616: Line 3,805:
}
}
pascal(8)
pascal(8)
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,629: Line 3,818:
</pre>
</pre>
====Recursive - memoized====
====Recursive - memoized====
<lang javascript>
<syntaxhighlight lang="javascript">
const aux = (() => {
const aux = (() => {
const layers = [[1], [1]]
const layers = [[1], [1]]
Line 3,646: Line 3,835:
}
}
pascal(8)
pascal(8)
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
Line 3,653: Line 3,842:
each corresponding to a row of the Pascal triangle.
each corresponding to a row of the Pascal triangle.
The implementation avoids any arithmetic except addition.
The implementation avoids any arithmetic except addition.
<lang jq># pascal(n) for n>=0; pascal(0) emits an empty stream.
<syntaxhighlight lang="jq"># pascal(n) for n>=0; pascal(0) emits an empty stream.
def pascal(n):
def pascal(n):
def _pascal: # input: the previous row
def _pascal: # input: the previous row
Line 3,663: Line 3,852:
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] | _pascal
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] | _pascal
end;
end;
if n <= 0 then empty else [1] | _pascal end ;</lang>
if n <= 0 then empty else [1] | _pascal end ;</syntaxhighlight>
'''Example''':
'''Example''':
pascal(5)
pascal(5)
{{ Out }}
{{ Out }}
<lang sh>$ jq -c -n -f pascal_triangle.jq
<syntaxhighlight lang="sh">$ jq -c -n -f pascal_triangle.jq
[1]
[1]
[1,1]
[1,1]
[1,2,1]
[1,2,1]
[1,3,3,1]
[1,3,3,1]
[1,4,6,4,1]</lang>
[1,4,6,4,1]</syntaxhighlight>


'''Using recurse/1'''
'''Using recurse/1'''


Here is an equivalent implementation that uses the built-in filter, recurse/1, instead of the inner function.
Here is an equivalent implementation that uses the built-in filter, recurse/1, instead of the inner function.
<lang jq>def pascal(n):
<syntaxhighlight lang="jq">def pascal(n):
if n <= 0 then empty
if n <= 0 then empty
else [1]
else [1]
Line 3,685: Line 3,874:
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1]
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1]
end)
end)
end;</lang>
end;</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Line 3,714: Line 3,903:
Another solution using matrix exponentiation.
Another solution using matrix exponentiation.


<syntaxhighlight lang="julia">
<lang Julia>
iround(x) = round(Int64, x)
iround(x) = round(Int64, x)


Line 3,724: Line 3,913:
end
end


</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 3,740: Line 3,929:
Yet another solution using a static vector
Yet another solution using a static vector


<syntaxhighlight lang="julia">
<lang Julia>
function pascal(n)
function pascal(n)
(n<=0) && error("Pascal trinalge can not have zero or negative rows")
(n<=0) && error("Pascal trinalge can not have zero or negative rows")
Line 3,756: Line 3,945:
end
end
end
end
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 3,773: Line 3,962:


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
pascal:{(x-1){+':x,0}\1}
pascal:{(x-1){+':x,0}\1}
pascal 6
pascal 6
Line 3,781: Line 3,970:
1 3 3 1
1 3 3 1
1 4 6 4 1
1 4 6 4 1
1 5 10 10 5 1)</lang>
1 5 10 10 5 1)</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang kotlin>fun pas(rows: Int) {
<syntaxhighlight lang="kotlin">fun pas(rows: Int) {
for (i in 0..rows - 1) {
for (i in 0..rows - 1) {
for (j in 0..i)
for (j in 0..i)
Line 3,801: Line 3,990:
}
}


fun main(args: Array<String>) = pas(args[0].toInt())</lang>
fun main(args: Array<String>) = pas(args[0].toInt())</syntaxhighlight>


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
1) Based on this expression of pascalian binomial:
1) Based on this expression of pascalian binomial:


Line 3,842: Line 4,031:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 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 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>input "How much rows would you like? "; n
<syntaxhighlight lang="lb">input "How much rows would you like? "; n
dim a$(n)
dim a$(n)


Line 3,863: Line 4,052:
next i
next i


end</lang>
end</syntaxhighlight>


=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==


<lang locobasic>10 CLS
<syntaxhighlight lang="locobasic">10 CLS
20 INPUT "Number of rows? ", rows:GOSUB 40
20 INPUT "Number of rows? ", rows:GOSUB 40
30 END
30 END
Line 3,878: Line 4,067:
100 PRINT
100 PRINT
110 NEXT
110 NEXT
120 RETURN</lang>
120 RETURN</syntaxhighlight>


Output:
Output:
Line 3,894: Line 4,083:


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to pascal :n
<syntaxhighlight lang="logo">to pascal :n
if :n = 1 [output [1]]
if :n = 1 [output [1]]
localmake "a pascal :n-1
localmake "a pascal :n-1
Line 3,900: Line 4,089:
end
end


for [i 1 10] [print pascal :i]</lang>
for [i 1 10] [print pascal :i]</syntaxhighlight>

=={{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}}==
=={{header|Lua}}==
<lang lua>
<syntaxhighlight lang="lua">
function nextrow(t)
function nextrow(t)
local ret = {}
local ret = {}
Line 3,918: Line 4,177:
end
end
end
end
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1);
<syntaxhighlight lang="maple">f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1);


f(3);</lang>
f(3);</syntaxhighlight>
1
1
1 1
1 1
Line 3,929: Line 4,188:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">n=7;
<lang Mathematica>n=7;
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[]:
A more graphical output with arrows would involve the plotting functionality with Graph[]:
<lang Mathematica>nmax := 10;
<syntaxhighlight lang="mathematica">nmax := 10;
pascal[nmax_] := Module[
pascal[nmax_] := Module[
{vals = Table[Binomial[n, k], {n, 0, nmax}, {k, 0, n}],
{vals = Table[Binomial[n, k], {n, 0, nmax}, {k, 0, n}],
Line 3,954: Line 4,213:
];
];
pascal[nmax]
pascal[nmax]
</syntaxhighlight>
</lang>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==


A matrix containing the pascal triangle can be obtained this way:
A matrix containing the pascal triangle can be obtained this way:
<lang MATLAB>pascal(n);</lang>
<syntaxhighlight lang="matlab">pascal(n);</syntaxhighlight>


<pre>>> pascal(6)
<pre>>> pascal(6)
Line 3,974: Line 4,233:


The binomial coefficients can be extracted from the Pascal triangle in this way:
The binomial coefficients can be extracted from the Pascal triangle in this way:
<lang MATLAB> binomCoeff = diag(rot90(pascal(n)))', </lang>
<syntaxhighlight lang="matlab"> binomCoeff = diag(rot90(pascal(n)))', </syntaxhighlight>


<pre>>> for k=1:6,diag(rot90(pascal(k)))', end
<pre>>> for k=1:6,diag(rot90(pascal(k)))', end
Line 4,024: Line 4,283:


=={{header|Maxima}}==
=={{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), " "));
display_pascal_triangle(n) := for i from 0 thru 6 do disp(sjoin(makelist(binomial(i, j), j, 0, i), " "));
Line 4,035: Line 4,295:
"1 4 6 4 1"
"1 4 6 4 1"
"1 5 10 10 5 1"
"1 5 10 10 5 1"
"1 6 15 20 15 6 1" */</lang>
"1 6 15 20 15 6 1" */
</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==
Line 4,041: Line 4,302:
(The formatting starts to be less clear when numbers start to have more than two digits)
(The formatting starts to be less clear when numbers start to have more than two digits)


<lang metafont>vardef bincoeff(expr n, k) =
<syntaxhighlight lang="metafont">vardef bincoeff(expr n, k) =
save ?;
save ?;
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor )
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor )
Line 4,058: Line 4,319:


pascaltr(4);
pascaltr(4);
end</lang>
end</syntaxhighlight>


=={{header|Microsoft Small Basic}}==
=={{header|Microsoft Small Basic}}==
{{trans|GW-BASIC}}
{{trans|GW-BASIC}}
<lang microsoftsmallbasic>
<syntaxhighlight lang="microsoftsmallbasic">
TextWindow.Write("Number of rows? ")
TextWindow.Write("Number of rows? ")
r = TextWindow.ReadNumber()
r = TextWindow.ReadNumber()
Line 4,074: Line 4,335:
TextWindow.WriteLine("")
TextWindow.WriteLine("")
EndFor
EndFor
</syntaxhighlight>
</lang>


Output:
Output:
Line 4,089: Line 4,350:


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE Pascal;
<syntaxhighlight lang="modula2">MODULE Pascal;
FROM FormatString IMPORT FormatString;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 4,121: Line 4,382:


ReadChar
ReadChar
END Pascal.</lang>
END Pascal.</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 4,164: Line 4,425:
end n_
end n_
return fac /*calc. factorial*/
return fac /*calc. factorial*/
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,184: Line 4,445:


(pascal.nial)
(pascal.nial)
<lang nial>factorial is recur [ 0 =, 1 first, pass, product, -1 +]
<syntaxhighlight lang="nial">factorial is recur [ 0 =, 1 first, pass, product, -1 +]
combination is fork [ > [first, second], 0 first,
combination is fork [ > [first, second], 0 first,
/ [factorial second, * [factorial - [second, first], factorial first] ]
/ [factorial second, * [factorial - [second, first], factorial first] ]
]
]
pascal is transpose each combination cart [pass, pass] tell</lang>
pascal is transpose each combination cart [pass, pass] tell</syntaxhighlight>
Using it
Using it
<lang nial>|loaddefs 'pascal.nial'
<syntaxhighlight lang="nial">|loaddefs 'pascal.nial'
|pascal 5</lang>
|pascal 5</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import sequtils, strutils
<syntaxhighlight lang="nim">import sequtils, strutils


proc printPascalTriangle(n: int) =
proc printPascalTriangle(n: int) =
Line 4,216: Line 4,477:
echo line.center(lineLength)
echo line.center(lineLength)


printPascalTriangle(10)</lang>
printPascalTriangle(10)</syntaxhighlight>


{{out}}
{{out}}
Line 4,231: Line 4,492:


A more optimized solution that doesn't require importing, but produces, naturally, uglier output, would look like this:
A more optimized solution that doesn't require importing, but produces, naturally, uglier output, would look like this:
<lang nim>const ROWS = 10
<syntaxhighlight lang="nim">const ROWS = 10
const TRILEN = toInt(ROWS * (ROWS + 1) / 2) # Sum of arth progression
const TRILEN = toInt(ROWS * (ROWS + 1) / 2) # Sum of arth progression
var triangle = newSeqOfCap[Natural](TRILEN) # Avoid reallocations
var triangle = newSeqOfCap[Natural](TRILEN) # Avoid reallocations
Line 4,243: Line 4,504:
if row + 1 <= ROWS: printPascalTri(row + 1, result)
if row + 1 <= ROWS: printPascalTri(row + 1, result)


printPascalTri(1, triangle)</lang>
printPascalTri(1, triangle)</syntaxhighlight>


{{out}}
{{out}}
Line 4,259: Line 4,520:
=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>(* generate next row from current row *)
<syntaxhighlight lang="ocaml">(* generate next row from current row *)
let next_row row =
let next_row row =
List.map2 (+) ([0] @ row) (row @ [0])
List.map2 (+) ([0] @ row) (row @ [0])
Line 4,268: Line 4,529:
if i = n then []
if i = n then []
else row :: loop (i+1) (next_row row)
else row :: loop (i+1) (next_row row)
in loop 0 [1]</lang>
in loop 0 [1]</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>function pascaltriangle(h)
<syntaxhighlight lang="octave">function pascaltriangle(h)
for i = 0:h-1
for i = 0:h-1
for k = 0:h-i
for k = 0:h-i
Line 4,283: Line 4,544:
endfunction
endfunction


pascaltriangle(4);</lang>
pascaltriangle(4);</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 4,289: Line 4,550:
No result if n <= 0
No result if n <= 0


<lang Oforth>: pascal(n) [ 1 ] #[ dup println dup 0 + 0 rot + zipWith(#+) ] times(n) drop ;</lang>
<syntaxhighlight lang="oforth">: pascal(n) [ 1 ] #[ dup println dup 0 + 0 rot + zipWith(#+) ] times(n) drop ;</syntaxhighlight>


{{out}}
{{out}}
Line 4,307: Line 4,568:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {NextLine Xs}
fun {NextLine Xs}
{List.zip 0|Xs {Append Xs [0]}
{List.zip 0|Xs {Append Xs [0]}
Line 4,337: Line 4,598:
end
end
in
in
{PrintTriangle {Triangle 5}}</lang>
{PrintTriangle {Triangle 5}}</syntaxhighlight>


For n = 0, prints nothing. For negative n, throws an exception.
For n = 0, prints nothing. For negative n, throws an exception.


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>pascals_triangle(N)= {
<syntaxhighlight lang="parigp">pascals_triangle(N)= {
my(row=[],prevrow=[]);
my(row=[],prevrow=[]);
for(x=1,N,
for(x=1,N,
Line 4,356: Line 4,617:
print(row);
print(row);
);
);
}</lang>
}</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>Program PascalsTriangle(output);
<syntaxhighlight lang="pascal">Program PascalsTriangle(output);


procedure Pascal(r : Integer);
procedure Pascal(r : Integer);
Line 4,379: Line 4,640:
begin
begin
Pascal(9)
Pascal(9)
end.</lang>
end.</syntaxhighlight>
Output:
Output:
<pre>% ./PascalsTriangle
<pre>% ./PascalsTriangle
Line 4,395: Line 4,656:
=={{header|Perl}}==
=={{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).
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).
<lang perl>sub pascal {
<syntaxhighlight lang="perl">sub pascal {
my $rows = shift;
my $rows = shift;
my @next = (1);
my @next = (1);
Line 4,402: Line 4,663:
@next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1);
@next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1);
}
}
}</lang>
}</syntaxhighlight>


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:
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}}
{{libheader|ntheory}}
<lang perl>use ntheory qw/binomial/;
<syntaxhighlight lang="perl">use ntheory qw/binomial/;
sub pascal {
sub pascal {
my $rows = shift;
my $rows = shift;
Line 4,412: Line 4,673:
print join(" ", map { binomial($n,$_) } 0 .. $n), "\n";
print join(" ", map { binomial($n,$_) } 0 .. $n), "\n";
}
}
}</lang>
}</syntaxhighlight>


Here is a non-obvious version using bignum, which is limited to the first 23 rows because of the algorithm used:
Here is a non-obvious version using bignum, which is limited to the first 23 rows because of the algorithm used:
<lang perl>use bignum;
<syntaxhighlight lang="perl">use bignum;
sub pascal_line { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 }
sub pascal_line { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 }
sub pascal { print "@{[map -+-$_, pascal_line $_]}\n" for 0..$_[0]-1 }</lang>
sub pascal { print "@{[map -+-$_, pascal_line $_]}\n" for 0..$_[0]-1 }</syntaxhighlight>


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


<lang perl>
<syntaxhighlight lang="perl">
#!/usr/bin/perl
#!/usr/bin/perl
use strict;
use strict;
Line 4,456: Line 4,717:
my @third = tartaglia_row(5);
my @third = tartaglia_row(5);
print "@third\n";
print "@third\n";
</syntaxhighlight>
</lang>


which output
which output
Line 4,473: Line 4,734:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">row</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">row</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<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>
<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>
Line 4,486: Line 4,747:
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre style="font-size: 8px">
<pre style="font-size: 8px">
Line 4,507: Line 4,768:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<syntaxhighlight lang="php">
<?php
<?php
//Author Ivan Gavryshin @dcc0
//Author Ivan Gavryshin @dcc0
Line 4,553: Line 4,814:
?>
?>
</lang> =={{header|PHP}}==
</syntaxhighlight> =={{header|PHP}}==
<lang php>function pascalsTriangle($num){
<syntaxhighlight lang="php">function pascalsTriangle($num){
$c = 1;
$c = 1;
$triangle = Array();
$triangle = Array();
Line 4,576: Line 4,837:
}
}
echo '<br>';
echo '<br>';
}</lang>
}</syntaxhighlight>
1
1
1 1
1 1
Line 4,586: Line 4,847:
1 7 21 35 35 21 7 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 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}}==
=={{header|PicoLisp}}==
{{trans|C}}
{{trans|C}}
<lang PicoLisp>(de pascalTriangle (N)
<syntaxhighlight lang="picolisp">(de pascalTriangle (N)
(for I N
(for I N
(space (* 2 (- N I)))
(space (* 2 (- N I)))
Line 4,596: Line 4,885:
(prin (align 3 C) " ")
(prin (align 3 C) " ")
(setq C (*/ C (- I K) K)) ) )
(setq C (*/ C (- I K) K)) ) )
(prinl) ) )</lang>
(prinl) ) )</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare (t, u)(40) fixed binary;
declare (t, u)(40) fixed binary;
declare (i, n) fixed binary;
declare (i, n) fixed binary;
Line 4,615: Line 4,904:
t = u;
t = u;
end;
end;
</syntaxhighlight>
</lang>


<lang>
<syntaxhighlight lang="text">
1
1
1 1
1 1
Line 4,629: Line 4,918:
1 9 36 84 126 126 84 36 9 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 10 45 120 210 252 210 120 45 10 1
</syntaxhighlight>
</lang>


=={{header|Potion}}==
=={{header|Potion}}==
<lang potion>printpascal = (n) :
<syntaxhighlight lang="potion">printpascal = (n) :
if (n < 1) :
if (n < 1) :
1 print
1 print
Line 4,649: Line 4,938:
.
.


printpascal(read number integer)</lang>
printpascal(read number integer)</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>
<syntaxhighlight lang="powershell">
$Infinity = 1
$Infinity = 1
$NewNumbers = $null
$NewNumbers = $null
Line 4,717: Line 5,006:
$Infinity++
$Infinity++
}
}
</syntaxhighlight>
</lang>


Save the above code to a .ps1 script file and start it by calling its name and providing N.
Save the above code to a .ps1 script file and start it by calling its name and providing N.
Line 4,746: Line 5,035:
=={{header|Prolog}}==
=={{header|Prolog}}==
Difference-lists are used to make quick append.
Difference-lists are used to make quick append.
<lang Prolog>pascal(N) :-
<syntaxhighlight lang="prolog">pascal(N) :-
pascal(1, N, [1], [[1]|X]-X, L),
pascal(1, N, [1], [[1]|X]-X, L),
maplist(my_format, L).
maplist(my_format, L).
Line 4,782: Line 5,071:
my_writef(X) :-
my_writef(X) :-
writef(' %5r', [X]).
writef(' %5r', [X]).
</syntaxhighlight>
</lang>


Output :
Output :
<lang Prolog> ?- pascal(15).
<syntaxhighlight lang="prolog"> ?- pascal(15).
1
1
1 1
1 1
Line 4,803: Line 5,092:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
true.
true.
</syntaxhighlight>
</lang>
===An alternative===
===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.
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.
<lang prolog>%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<syntaxhighlight lang="prolog">%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Produce a pascal's triangle of depth N
% Produce a pascal's triangle of depth N
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Line 4,834: Line 5,123:
pascal(N, Triangle), member(Row, Triangle), % Iterate and write each row
pascal(N, Triangle), member(Row, Triangle), % Iterate and write each row
write(Row), nl, fail.
write(Row), nl, fail.
pascal(_).</lang>
pascal(_).</syntaxhighlight>
*Output*:
*Output*:
<lang prolog>?- pascal(5).
<syntaxhighlight lang="prolog">?- pascal(5).
[1]
[1]
[1,1]
[1,1]
[1,2,1]
[1,2,1]
[1,3,3,1]
[1,3,3,1]
[1,4,6,4,1]</lang>
[1,4,6,4,1]</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==


<lang PureBasic>Procedure pascaltriangle( n.i)
<syntaxhighlight lang="purebasic">Procedure pascaltriangle( n.i)
For i= 0 To n
For i= 0 To n
Line 4,861: Line 5,150:
Parameter.i = Val(ProgramParameter(0))
Parameter.i = Val(ProgramParameter(0))
pascaltriangle(Parameter);
pascaltriangle(Parameter);
Input()</lang>
Input()</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
===Procedural===
===Procedural===
<lang python>def pascal(n):
<syntaxhighlight lang="python">def pascal(n):
"""Prints out n rows of Pascal's triangle.
"""Prints out n rows of Pascal's triangle.
It returns False for failure and True for success."""
It returns False for failure and True for success."""
Line 4,873: Line 5,162:
print row
print row
row=[l+r for l,r in zip(row+k,k+row)]
row=[l+r for l,r in zip(row+k,k+row)]
return n>=1</lang>
return n>=1</syntaxhighlight>


or by creating a scan function:
or by creating a scan function:
<lang Python>def scan(op, seq, it):
<syntaxhighlight lang="python">def scan(op, seq, it):
a = []
a = []
result = it
result = it
Line 4,892: Line 5,181:


for row in pascal(4):
for row in pascal(4):
print(row)</lang>
print(row)</syntaxhighlight>


===Functional===
===Functional===
Line 4,899: Line 5,188:


{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Pascal's triangle'''
<syntaxhighlight lang="python">'''Pascal's triangle'''


from itertools import (accumulate, chain, islice)
from itertools import (accumulate, chain, islice)
Line 4,995: Line 5,284:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre> 1
<pre> 1
Line 5,013: Line 5,302:


=={{header|q}}==
=={{header|q}}==
<syntaxhighlight lang="q">
<lang q>
pascal:{(x-1){0+':x,0}\1}
pascal:{(x-1){0+':x,0}\1}
pascal 5
pascal 5
Line 5,021: Line 5,310:
1 3 3 1
1 3 3 1
1 4 6 4 1
1 4 6 4 1
</syntaxhighlight>
</lang>


=={{header|Qi}}==
=={{header|Qi}}==
{{trans|Haskell}}
{{trans|Haskell}}
<syntaxhighlight lang="qi">
<lang Qi>
(define iterate
(define iterate
_ _ 0 -> []
_ _ 0 -> []
Line 5,035: Line 5,324:
(define pascal
(define pascal
N -> (iterate next-row [1] N))
N -> (iterate next-row [1] N))
</syntaxhighlight>
</lang>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 5,041: Line 5,330:
The behaviour of <code>pascal</code> for values less than 1 is the same as its behaviour for 1.
The behaviour of <code>pascal</code> for values less than 1 is the same as its behaviour for 1.


<lang Quackery> [ over size -
<syntaxhighlight lang="quackery"> [ over size -
space swap of
space swap of
swap join ] is justify ( $ n --> )
swap join ] is justify ( $ n --> )
Line 5,062: Line 5,351:
echoline ] is pascal ( n --> )
echoline ] is pascal ( n --> )
16 pascal</lang>
16 pascal</syntaxhighlight>


{{out}}
{{out}}
Line 5,086: Line 5,375:
=={{header|R}}==
=={{header|R}}==
{{trans|Octave}}
{{trans|Octave}}
<lang R>pascalTriangle <- function(h) {
<syntaxhighlight lang="r">pascalTriangle <- function(h) {
for(i in 0:(h-1)) {
for(i in 0:(h-1)) {
s <- ""
s <- ""
Line 5,095: Line 5,384:
print(s)
print(s)
}
}
}</lang>
}</syntaxhighlight>


Here's an R version:
Here's an R version:


<lang R>pascalTriangle <- function(h) {
<syntaxhighlight lang="r">pascalTriangle <- function(h) {
lapply(0:h, function(i) choose(i, 0:i))
lapply(0:h, function(i) choose(i, 0:i))
}</lang>
}</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 5,107: Line 5,396:
Iterative version by summing rows up to <math>n</math>.
Iterative version by summing rows up to <math>n</math>.


<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define (pascal n)
(define (pascal n)
Line 5,119: Line 5,408:




</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 5,127: Line 5,416:


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:
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:
<lang perl6>sub pascal {
<syntaxhighlight lang="raku" line>sub pascal {
[1], { [0, |$_ Z+ |$_, 0] } ... *
[1], { [0, |$_ Z+ |$_, 0] } ... *
}
}
.say for pascal[^10];</lang>
.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:
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:


<lang perl6>constant @pascal = [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... *;
<syntaxhighlight lang="raku" line>constant @pascal = [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... *;
.say for @pascal[^10];</lang>
.say for @pascal[^10];</syntaxhighlight>


Since we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error.
Since we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error.
Line 5,145: Line 5,434:
{{trans|Haskell}}
{{trans|Haskell}}


<lang perl6>multi sub pascal (1) { $[1] }
<syntaxhighlight lang="raku" line>multi sub pascal (1) { $[1] }
multi sub pascal (Int $n where 2..*) {
multi sub pascal (Int $n where 2..*) {
my @rows = pascal $n - 1;
my @rows = pascal $n - 1;
Line 5,151: Line 5,440:
}
}
.say for pascal 10;</lang>
.say for pascal 10;</syntaxhighlight>


Non-positive inputs throw a multiple-dispatch error.
Non-positive inputs throw a multiple-dispatch error.
Line 5,158: Line 5,447:


{{trans|Perl}}
{{trans|Perl}}
<lang perl6>sub pascal ($n where $n >= 1) {
<syntaxhighlight lang="raku" line>sub pascal ($n where $n >= 1) {
say my @last = 1;
say my @last = 1;
for 1 .. $n - 1 -> $row {
for 1 .. $n - 1 -> $row {
Line 5,166: Line 5,455:
}
}
pascal 10;</lang>
pascal 10;</syntaxhighlight>


Non-positive inputs throw a type check error.
Non-positive inputs throw a type check error.
Line 5,195: Line 5,484:
RapidQ does not require simple variables to be declared before use.
RapidQ does not require simple variables to be declared before use.


<lang rapidq>DEFINT values(100) = {0,1}
<syntaxhighlight lang="rapidq">DEFINT values(100) = {0,1}


INPUT "Number of rows: "; nrows
INPUT "Number of rows: "; nrows
Line 5,206: Line 5,495:
NEXT i
NEXT i
PRINT
PRINT
NEXT row</lang>
NEXT row</syntaxhighlight>


===Using binary coefficients===
===Using binary coefficients===
{{trans|BASIC}}
{{trans|BASIC}}
<lang rapidq>INPUT "Number of rows: "; nrows
<syntaxhighlight lang="rapidq">INPUT "Number of rows: "; nrows
FOR row = 0 TO nrows-1
FOR row = 0 TO nrows-1
c = 1
c = 1
Line 5,219: Line 5,508:
NEXT i
NEXT i
PRINT
PRINT
NEXT row</lang>
NEXT row</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>Red[]
<syntaxhighlight lang="red">Red[]
pascal-triangle: function [
pascal-triangle: function [
n [ integer! ] "number of rows"
n [ integer! ] "number of rows"
Line 5,235: Line 5,524:
row: left + right
row: left + right
]
]
]</lang>
]</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 5,249: Line 5,538:


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>2 elements i j
<syntaxhighlight lang="retro">2 elements i j
: pascalTriangle
: pascalTriangle
cr dup
cr dup
[ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop
[ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop
;
;
13 pascalTriangle</lang>
13 pascalTriangle</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 5,271: Line 5,560:
:::* &nbsp; Tartaglia's triangle
:::* &nbsp; Tartaglia's triangle
:::* &nbsp; Yang Hui's triangle
:::* &nbsp; Yang Hui's triangle
<lang rexx>/*REXX program displays (or writes to a file) Pascal's triangle (centered/formatted).*/
<syntaxhighlight lang="rexx">/*REXX program displays (or writes to a file) Pascal's triangle (centered/formatted).*/
numeric digits 3000 /*be able to handle gihugeic triangles.*/
numeric digits 3000 /*be able to handle gihugeic triangles.*/
parse arg nn . /*obtain the optional argument from CL.*/
parse arg nn . /*obtain the optional argument from CL.*/
Line 5,294: Line 5,583:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure; !=1; do j=2 to arg(1); != !*j; end /*j*/; return ! /*compute factorial*/</lang>
!: procedure; !=1; do j=2 to arg(1); != !*j; end /*j*/; return ! /*compute factorial*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 11 </tt>}}
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 11 </tt>}}
<pre>
<pre>
Line 5,338: Line 5,627:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
row = 5
row = 5
for i = 0 to row - 1
for i = 0 to row - 1
Line 5,349: Line 5,638:
see nl
see nl
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,358: Line 5,647:
1 4 6 4 1
1 4 6 4 1
</pre>
</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}}==
=={{header|Ruby}}==
<lang ruby>def pascal(n)
<syntaxhighlight lang="ruby">def pascal(n)
raise ArgumentError, "must be positive." if n < 1
raise ArgumentError, "must be positive." if n < 1
yield ar = [1]
yield ar = [1]
Line 5,369: Line 5,683:
end
end
pascal(8){|row| puts row.join(" ").center(20)}</lang>
pascal(8){|row| puts row.join(" ").center(20)}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,384: Line 5,698:
Or for more or less a translation of the two line Haskell version (with inject being abused a bit I know):
Or for more or less a translation of the two line Haskell version (with inject being abused a bit I know):


<lang ruby>def next_row(row) ([0] + row).zip(row + [0]).collect {|l,r| l + r } end
<syntaxhighlight 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
def pascal(n) n.times.inject([1]) {|x,_| next_row x } end


8.times{|i| p pascal(i)}</lang>
8.times{|i| p pascal(i)}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,402: Line 5,716:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>input "number of rows? ";r
<syntaxhighlight lang="runbasic">input "number of rows? ";r
for i = 0 to r - 1
for i = 0 to r - 1
c = 1
c = 1
Line 5,411: Line 5,725:
next
next
print
print
next</lang>Output:
next</syntaxhighlight>Output:
<pre>Number of rows? ?5
<pre>Number of rows? ?5
1
1
Line 5,421: Line 5,735:
=={{header|Rust}}==
=={{header|Rust}}==
{{trans|C}}
{{trans|C}}
<lang rust>
<syntaxhighlight lang="rust">
fn pascal_triangle(n: u64)
fn pascal_triangle(n: u64)
{
{
Line 5,437: Line 5,751:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
===Functional solutions===
===Functional solutions===
====Summing: Recursive row definition====
====Summing: Recursive row definition====
<lang scala>
<syntaxhighlight lang="scala">
def tri(row: Int): List[Int] =
def tri(row: Int): List[Int] =
row match {
row match {
case 1 => List(1)
case 1 => List(1)
case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1
case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1
}</lang>
}</syntaxhighlight>
Function to pretty print n rows:
Function to pretty print n rows:
<lang scala>def prettyTri(n:Int) = (1 to n) foreach {i => print(" "*(n-i)); tri(i) map (c => print(c + " ")); println}
<syntaxhighlight lang="scala">def prettyTri(n:Int) = (1 to n) foreach {i => print(" "*(n-i)); tri(i) map (c => print(c + " ")); println}


prettyTri(5)</lang>
prettyTri(5)</syntaxhighlight>
{{Out}}
{{Out}}
<pre> 1
<pre> 1
Line 5,459: Line 5,773:
1 4 6 4 1</pre>
1 4 6 4 1</pre>
====Summing: Scala Stream (Recursive & Memoization)====
====Summing: Scala Stream (Recursive & Memoization)====
<lang Scala>object Blaise extends App {
<syntaxhighlight lang="scala">object Blaise extends App {
def pascalTriangle(): Stream[Vector[Int]] =
def pascalTriangle(): Stream[Vector[Int]] =
Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1)
Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1)
Line 5,468: Line 5,782:
println("Pascal's Triangle")
println("Pascal's Triangle")
output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line"))
output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line"))
}</lang>
}</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)].
{{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}}==
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
{{Works with|Scheme|R<math>^5</math>RS}}
<lang scheme>(define (next-row row)
<syntaxhighlight lang="scheme">(define (next-row row)
(map + (cons 0 row) (append row '(0))))
(map + (cons 0 row) (append row '(0))))
Line 5,482: Line 5,796:


(triangle (list 1) 5)
(triangle (list 1) 5)
</syntaxhighlight>
</lang>
Output:
Output:
<lang>((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))</lang>
<syntaxhighlight lang="text">((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 5,508: Line 5,822:
writeln;
writeln;
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func pascal(rows) {
<syntaxhighlight lang="ruby">func pascal(rows) {
var row = [1]
var row = [1]
{ | n|
{ | n|
Line 5,519: Line 5,833:
}
}
 
 
pascal(10)</lang>
pascal(10)</syntaxhighlight>


=={{header|Stata}}==
=={{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).
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).


<lang stata>function pascal1(n) {
<syntaxhighlight lang="stata">function pascal1(n) {
return(comb(J(1,n,0::n-1),J(n,1,0..n-1)))
return(comb(J(1,n,0::n-1),J(n,1,0..n-1)))
}
}
Line 5,549: Line 5,863:
}
}
return(s)
return(s)
}</lang>
}</syntaxhighlight>


Now print the Pascal triangle.
Now print the Pascal triangle.


<lang stata>function print_pascal_triangle(n) {
<syntaxhighlight lang="stata">function print_pascal_triangle(n) {
a = pascal1(n)
a = pascal1(n)
for (i=1; i<=n; i++) {
for (i=1; i<=n; i++) {
Line 5,568: Line 5,882:
1 2 1
1 2 1
1 3 3 1
1 3 3 1
1 4 6 4 1</lang>
1 4 6 4 1</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>func pascal(n:Int)->[Int]{
<syntaxhighlight lang="swift">func pascal(n:Int)->[Int]{
if n==1{
if n==1{
let a=[1]
let a=[1]
Line 5,593: Line 5,907:
}
}
let waste = pascal(n:10)
let waste = pascal(n:10)
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
===Summing from Previous Rows===
===Summing from Previous Rows===
<lang tcl>proc pascal_iterative n {
<syntaxhighlight lang="tcl">proc pascal_iterative n {
if {$n < 1} {error "undefined behaviour for n < 1"}
if {$n < 1} {error "undefined behaviour for n < 1"}
set row [list 1]
set row [list 1]
Line 5,614: Line 5,928:
}
}


puts [join [pascal_iterative 6] \n]</lang>
puts [join [pascal_iterative 6] \n]</syntaxhighlight>
<pre>1
<pre>1
1 1
1 1
Line 5,623: Line 5,937:
===Using binary coefficients===
===Using binary coefficients===
{{trans|BASIC}}
{{trans|BASIC}}
<lang tcl>proc pascal_coefficients n {
<syntaxhighlight lang="tcl">proc pascal_coefficients n {
if {$n < 1} {error "undefined behaviour for n < 1"}
if {$n < 1} {error "undefined behaviour for n < 1"}
for {set i 0} {$i < $n} {incr i} {
for {set i 0} {$i < $n} {incr i} {
Line 5,637: Line 5,951:
}
}


puts [join [pascal_coefficients 6] \n]</lang>
puts [join [pascal_coefficients 6] \n]</syntaxhighlight>
===Combinations===
===Combinations===
{{trans|Java}}
{{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.
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.
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5


proc pascal_combinations n {
proc pascal_combinations n {
Line 5,675: Line 5,989:
}
}


puts [join [pascal_combinations 6] \n]</lang>
puts [join [pascal_combinations 6] \n]</syntaxhighlight>


===Comparing Performance===
===Comparing Performance===
<lang tcl>set n 100
<syntaxhighlight lang="tcl">set n 100
puts "calculate $n rows:"
puts "calculate $n rows:"
foreach proc {pascal_iterative pascal_coefficients pascal_combinations} {
foreach proc {pascal_iterative pascal_coefficients pascal_combinations} {
puts "$proc: [time [list $proc $n] 100]"
puts "$proc: [time [list $proc $n] 100]"
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>calculate 100 rows:
<pre>calculate 100 rows:
Line 5,691: Line 6,005:
=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
===Using Addition of Previous Rows===
===Using Addition of Previous Rows===
<lang ti83b>PROGRAM:PASCALTR
<syntaxhighlight lang="ti83b">PROGRAM:PASCALTR
:Lbl IN
:Lbl IN
:ClrHome
:ClrHome
Line 5,707: Line 6,021:
:End
:End
:End
:End
:[A]</lang>
:[A]</syntaxhighlight>
===Using nCr Function===
===Using nCr Function===
<lang ti83b>PROGRAM:PASCALTR
<syntaxhighlight lang="ti83b">PROGRAM:PASCALTR
:Lbl IN
:Lbl IN
:ClrHome
:ClrHome
Line 5,721: Line 6,035:
:End
:End
:End
:End
:[A]</lang>
:[A]</syntaxhighlight>


=={{header|Turing}}==
=={{header|Turing}}==


<lang turing>proc pascal (n : int)
<syntaxhighlight lang="turing">proc pascal (n : int)
for i : 0 .. n
for i : 0 .. n
var c := 1
var c := 1
Line 5,736: Line 6,050:
end pascal
end pascal


pascal(5)</lang>
pascal(5)</syntaxhighlight>


Output:
Output:
Line 5,748: Line 6,062:
== {{header|TypeScript}} ==
== {{header|TypeScript}} ==
{{trans|XPL0}}
{{trans|XPL0}}
<lang javascript>// Pascal's triangle
<syntaxhighlight lang="javascript">// Pascal's triangle


function pascal(n: number): void {
function pascal(n: number): void {
Line 5,779: Line 6,093:
pascal(13);
pascal(13);
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,798: Line 6,112:


=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
<lang>Input "Number Of Rows: "; N
<syntaxhighlight lang="text">Input "Number Of Rows: "; N
@(1) = 1
@(1) = 1
Print Tab((N+1)*3);"1"
Print Tab((N+1)*3);"1"
Line 5,811: Line 6,125:


Print
Print
End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>Number Of Rows: 10
<pre>Number Of Rows: 10
Line 5,831: Line 6,145:
{{works with|Bourne Again SHell}}
{{works with|Bourne Again SHell}}
Any n <= 1 will print the "1" row.
Any n <= 1 will print the "1" row.
<lang bash>#! /bin/bash
<syntaxhighlight lang="bash">#! /bin/bash
pascal() {
pascal() {
local -i n=${1:-1}
local -i n=${1:-1}
Line 5,848: Line 6,162:
fi
fi
}
}
pascal "$1"</lang>
pascal "$1"</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Zero maps to the empty list. Negatives are inexpressible.
Zero maps to the empty list. Negatives are inexpressible.
This solution uses a library function for binomial coefficients.
This solution uses a library function for binomial coefficients.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


pascal = choose**ziDS+ iota*t+ iota+ successor</lang>
pascal = choose**ziDS+ iota*t+ iota+ successor</syntaxhighlight>
This solution uses direct summation. The algorithm is to
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,
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.
map the sum over the list of pairs, iterate n times, and return the trace.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


pascal "n" = (next"n" sum*NiCixp) <1></lang>
pascal "n" = (next"n" sum*NiCixp) <1></syntaxhighlight>
test program:
test program:
<lang Ursala>#cast %nLL
<syntaxhighlight lang="ursala">#cast %nLL


example = pascal 10</lang>
example = pascal 10</syntaxhighlight>
{{Out}}
{{Out}}
<pre><
<pre><
Line 5,882: Line 6,196:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Option Base 1
<syntaxhighlight lang="vb">Option Base 1
Private Sub pascal_triangle(n As Integer)
Private Sub pascal_triangle(n As Integer)
Dim odd() As String
Dim odd() As String
Line 5,911: Line 6,225:
Public Sub main()
Public Sub main()
pascal_triangle 13
pascal_triangle 13
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre> 1
<pre> 1
1 1
1 1
Line 5,928: Line 6,242:
=={{header|VBScript}}==
=={{header|VBScript}}==
Derived from the BASIC version.
Derived from the BASIC version.
<lang vb>Pascal_Triangle(WScript.Arguments(0))
<syntaxhighlight lang="vb">Pascal_Triangle(WScript.Arguments(0))
Function Pascal_Triangle(n)
Function Pascal_Triangle(n)
Dim values(100)
Dim values(100)
Line 5,941: Line 6,255:
WScript.StdOut.WriteLine
WScript.StdOut.WriteLine
Next
Next
End Function</lang>
End Function</syntaxhighlight>
{{out}}
{{out}}
Invoke from a command line.
Invoke from a command line.
Line 5,962: Line 6,276:
For example, if #99 contains value 2, then #@99 accesses contents of numeric register #2.
For example, if #99 contains value 2, then #@99 accesses contents of numeric register #2.


<lang vedit>#100 = Get_Num("Number of rows: ", STATLINE)
<syntaxhighlight lang="vedit">#100 = Get_Num("Number of rows: ", STATLINE)
#0=0; #1=1
#0=0; #1=1
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1)
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1)
Line 5,974: Line 6,288:
}
}
Ins_Newline
Ins_Newline
}</lang>
}</syntaxhighlight>


===Using binary coefficients===
===Using binary coefficients===
{{trans|BASIC}}
{{trans|BASIC}}
<lang vedit>#1 = Get_Num("Number of rows: ", STATLINE)
<syntaxhighlight lang="vedit">#1 = Get_Num("Number of rows: ", STATLINE)
for (#2 = 0; #2 < #1; #2++) {
for (#2 = 0; #2 < #1; #2++) {
#3 = 1
#3 = 1
Line 5,987: Line 6,301:
}
}
Ins_Newline
Ins_Newline
}</lang>
}</syntaxhighlight>


=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
{{works with|Visual Basic|VB6 Standard}}
<lang vb>Sub pascaltriangle()
<syntaxhighlight lang="vb">Sub pascaltriangle()
'Pascal's triangle
'Pascal's triangle
Const m = 11
Const m = 11
Line 6,008: Line 6,322:
Next n
Next n
MsgBox ss, , "Pascal's triangle"
MsgBox ss, , "Pascal's triangle"
End Sub 'pascaltriangle</lang>
End Sub 'pascaltriangle</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,026: Line 6,340:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<lang vbnet>Imports System.Numerics
<syntaxhighlight lang="vbnet">Imports System.Numerics


Module Module1
Module Module1
Line 6,067: Line 6,381:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre> 1
<pre> 1
Line 6,092: Line 6,406:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
{{libheader|wren-math}}
{{libheader|Wren-math}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="wren">import "./fmt" for Fmt
import "/math" for Int
import "./math" for Int

var binomial = Fn.new { |n, k|
if (n == k) return 1
var prod = 1
var i = n - k + 1
while (i <= n) {
prod = prod * i
i = i + 1
}
return prod / Int.factorial(k)
}


var pascalTriangle = Fn.new { |n|
var pascalTriangle = Fn.new { |n|
Line 6,112: Line 6,415:
System.write(" " * (n-i-1))
System.write(" " * (n-i-1))
for (j in 0..i) {
for (j in 0..i) {
Fmt.write("$3d ", binomial.call(i, j))
Fmt.write("$3d ", Int.binomial(i, j))
}
}
System.print()
System.print()
Line 6,118: Line 6,421:
}
}


pascalTriangle.call(13)</lang>
pascalTriangle.call(13)</syntaxhighlight>


{{out}}
{{out}}
Line 6,141: Line 6,444:
{{works with|Windows}}
{{works with|Windows}}
<b>uses:</b> io.inc - Macro library from SASM
<b>uses:</b> io.inc - Macro library from SASM
<lang asm>
<syntaxhighlight lang="asm">
%include "io.inc"
%include "io.inc"


Line 6,220: Line 6,523:
pop ecx
pop ecx
ret
ret
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 6,235: Line 6,538:
{{trans|GW-BASIC}}
{{trans|GW-BASIC}}
{{works with|Windows XBasic}}
{{works with|Windows XBasic}}
<lang xbasic>
<syntaxhighlight lang="xbasic">
PROGRAM "pascal"
PROGRAM "pascal"
VERSION "0.0001"
VERSION "0.0001"
Line 6,253: Line 6,556:
END FUNCTION
END FUNCTION
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 6,267: Line 6,570:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;


proc Pascal(N); \Display the first N rows of Pascal's triangle
proc Pascal(N); \Display the first N rows of Pascal's triangle
Line 6,288: Line 6,591:
];
];


Pascal(13)</lang>
Pascal(13)</syntaxhighlight>


{{Out}}
{{Out}}
Line 6,309: Line 6,612:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|C}}
{{trans|C}}
<lang zkl>fcn pascalTriangle(n){ // n<=0-->""
<syntaxhighlight lang="zkl">fcn pascalTriangle(n){ // n<=0-->""
foreach i in (n){
foreach i in (n){
c := 1;
c := 1;
Line 6,321: Line 6,624:
}
}
pascalTriangle(8);</lang>
pascalTriangle(8);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,337: Line 6,640:


In edit mode insert:
In edit mode insert:
<lang BASIC> 10 INPUT "How many rows? ";n
<syntaxhighlight lang="basic"> 10 INPUT "How many rows? ";n
15 IF n<1 THEN GO TO 210
15 IF n<1 THEN GO TO 210
20 DIM c(n)
20 DIM c(n)
Line 6,360: Line 6,663:
180 LET c(i)=d(i)
180 LET c(i)=d(i)
190 NEXT i
190 NEXT i
200 NEXT r</lang>
200 NEXT r</syntaxhighlight>


Then in command mode (basically don't put a number in front):
Then in command mode (basically don't put a number in front):
<lang BASIC>RUN</lang>
<syntaxhighlight lang="basic">RUN</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>

Latest revision as of 11:07, 24 January 2024

Task
Pascal's triangle
You are encouraged to solve this task according to the task description, using any language you may know.

Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.

Its first few rows look like this:

    1
   1 1
  1 2 1
 1 3 3 1 

where each element of each row is either 1 or the sum of the two elements right above it.

For example, the next row of the triangle would be:

  1   (since the first element of each row doesn't have two elements above it)
  4   (1 + 3)
  6   (3 + 3)
  4   (3 + 1)
  1   (since the last element of each row doesn't have two elements above it)

So the triangle now looks like this:

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1 

Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n.


Task

Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1).

This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.

Behavior for   n ≤ 0   does not need to be uniform, but should be noted.


See also



11l

Translation of: Python
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)
Output:
       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

360 Assembly

Translation of: PL/I
*        Pascal's triangle         25/10/2015
PASCAL   CSECT
         USING  PASCAL,R15         set base register
         LA     R7,1               n=1
LOOPN    C      R7,=A(M)           do n=1 to m
         BH     ELOOPN             if n>m then goto 
         MVC    U,=F'1'            u(1)=1
         LA     R8,PG              pgi=@pg
         LA     R6,1               i=1
LOOPI    CR     R6,R7              do i=1 to n
         BH     ELOOPI             if i>n then goto 
         LR     R1,R6              i
         SLA    R1,2               i*4
         L      R3,T-4(R1)         t(i)
         L      R4,T(R1)           t(i+1)
         AR     R3,R4              t(i)+t(i+1)
         ST     R3,U(R1)           u(i+1)=t(i)+t(i+1)
         LR     R1,R6              i
         SLA    R1,2               i*4
         L      R2,U-4(R1)         u(i)
         XDECO  R2,XD              edit u(i)
         MVC    0(4,R8),XD+8       output u(i):4
         LA     R8,4(R8)           pgi=pgi+4
         LA     R6,1(R6)           i=i+1
         B      LOOPI              end i
ELOOPI   MVC    T((M+1)*(L'T)),U   t=u
         XPRNT  PG,80              print
         LA     R7,1(R7)           n=n+1
         B      LOOPN              end n
ELOOPN   XR     R15,R15            set return code
         BR     R14                return to caller
M        EQU    11                 <== input
T        DC     (M+1)F'0'          t(m+1) init 0
U        DC     (M+1)F'0'          u(m+1) init 0
PG       DC     CL80' '            pg     init ' '
XD       DS     CL12               temp
         YREGS
         END    PASCAL
Output:
   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

8th

One way, using array operations:

\ print the array 
: .arr \ a -- a 
  ( . space ) a:each ;

: pasc \ a --
  \ print the row
  .arr cr
  dup 
  \ create two rows from the first, one with a leading the other with a trailing 0
  [0] 0 a:insert swap 0 a:push
  \ add the arrays together to make the new one
  ' n:+ a:op ;

\ print the first 16 rows:
[1] ' pasc 16 times

Another way, using the relation between element 'n' and element 'n-1' in a row:

: ratio \ m n -- num denom
  tuck n:- n:1+ swap ;

\ one item in the row: n m
: pascitem \ n m -- n
	r@ swap 
	ratio 
	n:*/ n:round int
	dup . space ;

\ One row of Pascal's triangle
: pascline \ n --
	>r 1 int dup . space 
	' pascitem 
	1 r@ loop rdrop drop cr ;

\ Calculate the first 'n' rows of Pascal's triangle:
: pasc \ n 
	' pascline 0 rot loop cr ;

15 pasc

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
Output:

Screenshot from Atari 8-bit computer

                  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

Ada

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 [[1]]

package Pascal is
   
   type Row is array (Natural range <>) of Natural;
   
   function Length(R: Row) return Positive;
   
   function First_Row(Max_Length: Positive) return Row;
   
   function Next_Row(R: Row) return Row;
   
end Pascal;

The implementation of that auxiliary package "Pascal":

package body Pascal is
   
   function First_Row(Max_Length: Positive) return Row is
      R: Row(0 .. Max_Length) := (0 | 1 => 1, others => 0);
   begin
      return R;
   end First_Row;
   
   function Next_Row(R: Row) return Row is
      S: Row(R'Range);
   begin
      S(0) := Length(R)+1;
      S(Length(S)) := 1;
      for J in reverse 2 .. Length(R) loop
         S(J) := R(J)+R(J-1);
      end loop;
      S(1) := 1;
      return S;
   end Next_Row;
   
   function Length(R: Row) return Positive is
   begin
      return R(0);
   end Length;
   
end Pascal;

The main program, using "Pascal". It prints the desired number of rows. The number is read from the command line.

with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line, Pascal; use Pascal;

procedure Triangle is
   
   Number_Of_Rows: Positive := Integer'Value(Ada.Command_Line.Argument(1));
   Row: Pascal.Row := First_Row(Number_Of_Rows);
      
begin
   loop
      -- print one row
      for J in 1 .. Length(Row) loop
	 Ada.Integer_Text_IO.Put(Row(J), 5);
      end loop;
      Ada.Text_IO.New_Line;
      exit when Length(Row) >= Number_Of_Rows;
      Row := Next_Row(Row);
   end loop;
end Triangle;
Output:
>./triangle 12
    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

ALGOL 68

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);

OP + = ([]INT a,b)[]INT:(
  [a MINLWB b:a MAXUPB b]INT out; FOR i FROM LWB out TO UPB out DO out[i]:= 0 OD;
  out[LWB a:UPB a] := a; FOR i FROM LWB b TO UPB b DO out[i]+:= b[i] OD;
  out
);

INT width = 4, stop = 9;
FORMAT centre = $n((stop-UPB row+1)*width OVER 2)(q)$;

FLEX[1]INT row := 1; # example of rowing #
FOR i WHILE
  printf((centre, $g(-width)$, row, $l$));
# WHILE # i < stop DO
  row := row[AT 1] + row[AT 2]
OD
Output:
                     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

ALGOL W

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

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
Output:
$ 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

APL

Pascal' s triangle of order ⍵

Dyalog APL

{0~¨⍨(-⌽A)⌽↑,/0,¨A∘.!A0,⍳}

example

{0~¨⍨(-⌽A)⌽↑,/0,¨A∘.!A0,⍳}5
                   1                 
               1      1              
            1      2      1          
         1     3      3      1       
      1     4      6      4     1    
   1     5     10     10     5     1 

GNU APL

GNU APL doesn't allow multiple statements within lambdas so the solution is phrased differently:

{{∘.!} 0,⍳}

example

{{∘.!} 0,⍳} 3
1 0 0 0
1 1 0 0
1 2 1 0
1 3 3 1

AppleScript

Drawing n rows from a generator:

-------------------- PASCAL'S TRIANGLE -------------------

-- pascal :: Generator [[Int]]
on pascal()
    script nextRow
        on |λ|(row)
            zipWith(my plus, {0} & row, row & {0})
        end |λ|
    end script
    iterate(nextRow, {1})
end pascal


--------------------------- TEST -------------------------
on run
    showPascal(take(7, pascal()))
end run


------------------------ FORMATTING ----------------------

-- showPascal :: [[Int]] -> String
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|


-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map


-- min :: Ord a => a -> a -> a
on min(x, y)
    if y < x then
        y
    else
        x
    end if
end min


-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    -- 2nd class handler function lifted into 1st class script wrapper. 
    if script is class of f then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn



-- plus :: Num -> Num -> Num
on plus(a, b)
    a + b
end plus


-- 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 out & dbl
end replicate


-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
    set c to class of 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
        missing value
    end if
end 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
Output:
              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

Arturo

Translation of: Nim
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
]
Output:
                             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

AutoHotkey

ahk forum: discussion

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
   Loop Parse, %q%, %A_Space%
      If (A_Index > 1)
         %p% .= " " v+A_LoopField, v := A_LoopField
   %p% .= " 1"
}
                         ; Triangular Formatted output
VarSetCapacity(tabs,n,Asc("`t"))
t .= tabs "`t1"
Loop %n% {
   t .= "`n" SubStr(tabs,A_Index)
   Loop Parse, p%A_Index%, %A_Space%
      t .= A_LoopField "`t`t"
}
Gui Add, Text,, %t%      ; Show result in a GUI
Gui Show
Return

GuiClose:
  ExitApp

Alternate

Works with: AutoHotkey L
Msgbox % format(pascalstriangle())
Return

format(o) ; converts object to string
{
	For k, v in o
		s .= IsObject(v) ? format(v) "`n" : v " "
	Return s
}
pascalstriangle(n=7) ; n rows of Pascal's triangle
{
	p := Object(), z:=Object()
	Loop, % n
		Loop, % row := A_Index
			col := A_Index
			, p[row, col] := row = 1 and col = 1 
				? 1 
				: (p[row-1, col-1] = "" ; math operations on blanks return blanks; I want to assume zero
					? 0 
					: p[row-1, col-1])
				+ (p[row-1, col] = "" 
					? 0 
					: p[row-1, col]) 
	Return p
}

n <= 0 returns empty

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}}'
Output:

1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1


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))
}
Output:
      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


BASIC

Summing from Previous Rows

Works with: FreeBASIC

This implementation uses an array to store one row of the triangle. DIM initializes the array values to zero. For first row, "1" is then stored in the array. To calculate values for next row, the value in cell (i-1) is added to each cell (i). This summing is done from right to left so that it can be done on-place, without using a tmp buffer. Because of symmetry, the values can be displayed from left to right.

Space for max 5 digit numbers is reserved when formatting the display. The maximum size of triangle is 100 rows, but in practice it is limited by screen space. If the user enters value less than 1, the first row is still always displayed.

DIM i             AS Integer
DIM row           AS Integer
DIM nrows         AS Integer
DIM values(100)   AS Integer

INPUT "Number of rows: "; nrows
values(1) = 1
PRINT TAB((nrows)*3);"  1"
FOR row = 2 TO nrows
    PRINT TAB((nrows-row)*3+1);
    FOR i = row TO 1 STEP -1
        values(i) = values(i) + values(i-1)
        PRINT USING "##### "; values(i);
    NEXT i
    PRINT
NEXT row

Batch File

Based from the Fortran Code.

@echo off
setlocal enabledelayedexpansion

::The Main Thing...
cls
echo.
set row=15
call :pascal
echo.
pause
exit /b 0
::/The Main Thing.

::The Functions...
:pascal
	set /a prev=%row%-1
	for /l %%I in (0,1,%prev%) do (
		set c=1&set r=
		for /l %%K in (0,1,%row%) do (
			if not !c!==0 (
				call :numstr !c!
				set r=!r!!space!!c!
			)
			set /a c=!c!*^(%%I-%%K^)/^(%%K+1^)
		)
		echo !r!
	)
goto :EOF

:numstr
	::This function returns the number of whitespaces to be applied on each numbers.
	set cnt=0&set proc=%1&set space=
	:loop
	set currchar=!proc:~%cnt%,1!
	if not "!currchar!"=="" set /a cnt+=1&goto loop
	set /a numspaces=5-!cnt!
	for /l %%A in (1,1,%numspaces%) do set "space=!space! "
goto :EOF
::/The Functions.
Output:
    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

Press any key to continue . . .

BBC BASIC

      nrows% = 10
      
      colwidth% = 4
      @% = colwidth% : REM Set column width
      FOR row% = 1 TO nrows%
        PRINT SPC(colwidth%*(nrows% - row%)/2);
        acc% = 1
        FOR element% = 1 TO row%
          PRINT acc%;
          acc% = acc% * (row% - element%) / element% + 0.5
        NEXT
        PRINT
      NEXT row%
Output:
                     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

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)
Output:
                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

Befunge

0" :swor fo rebmuN">:#,_&> 55+, v
v01*p00-1:g00.:<1p011p00:\-1_v#:<
>g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@
Output:
Number of rows: 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  

BQN

Displays n rows.

Pascal  {(0∾+∾0)(𝕩)1}

•Show¨Pascal 6
⟨ 1 ⟩
⟨ 1 1 ⟩
⟨ 1 2 1 ⟩
⟨ 1 3 3 1 ⟩
⟨ 1 4 6 4 1 ⟩
⟨ 1 5 10 10 5 1 ⟩

Bracmat

( out$"Number of rows? "
& get':?R
& -1:?I
&   whl
  ' ( 1+!I:<!R:?I
    & 1:?C
    & -1:?K
    & !R+-1*!I:?tabs
    & whl'(!tabs+-1:>0:?tabs&put$\t)
    &   whl
      ' ( 1+!K:~>!I:?K
        & put$(!C \t\t)
        & !C*(!I+-1*!K)*(!K+1)^-1:?C
        )
    & put$\n
    )
&
)
Output:
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

Burlesque

blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S
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

C

Translation of: Fortran
#include <stdio.h>

void pascaltriangle(unsigned int n)
{
  unsigned int c, i, j, k;

  for(i=0; i < n; i++) {
    c = 1;
    for(j=1; j <= 2*(n-1-i); j++) printf(" ");
    for(k=0; k <= i; k++) {
      printf("%3d ", c);
      c = c * (i-k)/(k+1);
    }
    printf("\n");
  }
}

int main()
{
  pascaltriangle(8);
  return 0;
}

Recursive

#include <stdio.h>

#define D 32
int pascals(int *x, int *y, int d)
{
	int i;
	for (i = 1; i < d; i++)
		printf("%d%c", y[i] = x[i - 1] + x[i],
			i < d - 1 ? ' ' : '\n');

	return D > d ? pascals(y, x, d + 1) : 0;
}

int main()
{
	int x[D] = {0, 1, 0}, y[D] = {0};
	return pascals(x, y, 0);
}

Adding previous row values

void triangleC(int nRows) {
    if (nRows <= 0) return;
    int *prevRow = NULL;
    for (int r = 1; r <= nRows; r++) {
        int *currRow = malloc(r * sizeof(int));
        for (int i = 0; i < r; i++) {
            int val = i==0 || i==r-1 ? 1 : prevRow[i-1] + prevRow[i];
            currRow[i] = val;
            printf(" %4d", val);
        }
        printf("\n");
        free(prevRow);
        prevRow = currRow;
    }
    free(prevRow);
}

C#

Translation of: Fortran

Produces no output when n is less than or equal to zero.

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);
        }
    }
}

Arbitrarily large numbers (BigInteger), arbitrary row selection

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);
		}
	}
}

Example:

static void Main()
{
	IEnumerable<BigInteger[]> triangle = PascalsTriangle.GetTriangle(20);
	string output = PascalsTriangle.FormatTriangleString(triangle)
	Console.WriteLine(output);
}
Output:
                                                           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  

C++

#include <iostream>
#include <algorithm>
#include<cstdio>
using namespace std;
void Pascal_Triangle(int size) {

	int a[100][100];
	int i, j;

	//first row and first coloumn has the same value=1
	for (i = 1; i <= size; i++) {
		a[i][1] = a[1][i] = 1;
	}
	
	//Generate the full Triangle
	for (i = 2; i <= size; i++) {
		for (j = 2; j <= size - i; j++) {
			if (a[i - 1][j] == 0 || a[i][j - 1] == 0) {
				break;
			}
			a[i][j] = a[i - 1][j] + a[i][j - 1];
		}
	}

	/* 
	  1 1 1 1
	  1 2 3
	  1 3
	  1
	 
	first print as above format-->
	 
	for (i = 1; i < size; i++) {
		for (j = 1; j < size; j++) {
			if (a[i][j] == 0) {
					break;
			}
				printf("%8d",a[i][j]);
		}
			cout<<"\n\n";
	}*/
	
	// standard Pascal Triangle Format 
	
	int row,space;
	for (i = 1; i < size; i++) {
		space=row=i;
		j=1;
		
		while(space<=size+(size-i)+1){
			 cout<<" ";
			 space++;
		 }
		
		while(j<=i){
			if (a[row][j] == 0){
				   break;
			   }
			
			if(j==1){
				printf("%d",a[row--][j++]);
			}
			else
				printf("%6d",a[row--][j++]);
		}
			cout<<"\n\n";
	}
	
}

int main()
{
	//freopen("out.txt","w",stdout);
	
	int size;
	cin>>size;
	Pascal_Triangle(size);
}

}

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.

// Compile with -std=c++11
#include<iostream>
#include<vector>
using namespace std;
void print_vector(vector<int> dummy){
	for (vector<int>::iterator i = dummy.begin(); i != dummy.end(); ++i)
		cout<<*i<<" ";
	cout<<endl;
}
void print_vector_of_vectors(vector<vector<int>> dummy){
	for (vector<vector<int>>::iterator i = dummy.begin(); i != dummy.end(); ++i)
		print_vector(*i);
	cout<<endl;
}
vector<vector<int>> dynamic_triangle(int dummy){
	vector<vector<int>> result;
	if (dummy > 0){ // if the argument is 0 or negative exit immediately
		vector<int> row;
		// The first row
		row.push_back(1);
		result.push_back(row);
		// The second row
		if (dummy > 1){
			row.clear();
			row.push_back(1); row.push_back(1);
			result.push_back(row);
		}
		// The other rows
		if (dummy > 2){
			for (int i = 2; i < dummy; i++){
				row.clear();
				row.push_back(1);
				for (int j = 1; j < i; j++)
					row.push_back(result.back().at(j - 1) + result.back().at(j));
				row.push_back(1);
				result.push_back(row);
			}
		}
	}
	return result;
}
vector<vector<int>> static_triangle(int dummy){
	vector<vector<int>> result;
	if (dummy > 0){ // if the argument is 0 or negative exit immediately
		vector<int> row;
		result.resize(dummy); // This should work faster than consecutive push_back()s
		// The first row
		row.resize(1);
		row.at(0) = 1;
		result.at(0) = row;
		// The second row
		if (result.size() > 1){
			row.resize(2);
			row.at(0) = 1; row.at(1) = 1;
			result.at(1) = row;
		}
		// The other rows
		if (result.size() > 2){
			for (int i = 2; i < result.size(); i++){
				row.resize(i + 1); // This should work faster than consecutive push_back()s
				row.front() = 1;
				for (int j = 1; j < row.size() - 1; j++)
					row.at(j) = result.at(i - 1).at(j - 1) + result.at(i - 1).at(j);
				row.back() = 1;
				result.at(i) = row;
			}
		}
	}
	return result;
}
int main(){
	vector<vector<int>> triangle;
	int n;
	cout<<endl<<"The Pascal's Triangle"<<endl<<"Enter the number of rows: ";
	cin>>n;
	// Call the dynamic function
	triangle = dynamic_triangle(n);
	cout<<endl<<"Calculated using dynamic vectors:"<<endl<<endl;
	print_vector_of_vectors(triangle);
	// Call the static function
	triangle = static_triangle(n);
	cout<<endl<<"Calculated using static vectors:"<<endl<<endl;
	print_vector_of_vectors(triangle);
	return 0;
}

C++11 (with a class)

A full fledged example with a class definition and methods to retrieve data, worthy of the title object-oriented.

// Compile with -std=c++11
#include<iostream>
#include<vector>
using namespace std;
class pascal_triangle{
	vector<vector<int>> data; // This is the actual data
	void print_row(vector<int> dummy){
		for (vector<int>::iterator i = dummy.begin(); i != dummy.end(); ++i)
			cout<<*i<<" ";
		cout<<endl;
	}
public:
	pascal_triangle(int dummy){ // Everything is done on the construction phase
		if (dummy > 0){ // if the argument is 0 or negative exit immediately
			vector<int> row;
			data.resize(dummy); // Theoretically this should work faster than consecutive push_back()s
			// The first row
			row.resize(1);
			row.at(0) = 1;
			data.at(0) = row;
			// The second row
			if (data.size() > 1){
				row.resize(2);
				row.at(0) = 1; row.at(1) = 1;
				data.at(1) = row;
			}
			// The other rows
			if (data.size() > 2){
				for (int i = 2; i < data.size(); i++){
					row.resize(i + 1); // Theoretically this should work faster than consecutive push_back()s
					row.front() = 1;
					for (int j = 1; j < row.size() - 1; j++)
						row.at(j) = data.at(i - 1).at(j - 1) + data.at(i - 1).at(j);
					row.back() = 1;
					data.at(i) = row;
				}
			}
		}
	}
	~pascal_triangle(){
		for (vector<vector<int>>::iterator i = data.begin(); i != data.end(); ++i)
			i->clear(); // I'm not sure about the necessity of this loop!
		data.clear();
	}
	void print_row(int dummy){
		if (dummy < data.size())
			for (vector<int>::iterator i = data.at(dummy).begin(); i != data.at(dummy).end(); ++i)
				cout<<*i<<" ";
		cout<<endl;
	}
	void print(){
		for (int i = 0; i < data.size(); i++)
			print_row(i);
	}
	int get_coeff(int dummy1, int dummy2){
		int result = 0;
		if ((dummy1 < data.size()) && (dummy2 < data.at(dummy1).size()))
				result = data.at(dummy1).at(dummy2);
		return result;
	}
	vector<int> get_row(int dummy){
		vector<int> result;
		if (dummy < data.size())
			result = data.at(dummy);
		return result;
	}
};
int main(){
	int n;
	cout<<endl<<"The Pascal's Triangle with a class!"<<endl<<endl<<"Enter the number of rows: ";
	cin>>n;
	pascal_triangle myptri(n);
	cout<<endl<<"The whole triangle:"<<endl;
	myptri.print();
	cout<<endl<<"Just one row:"<<endl;
	myptri.print_row(n/2);
	cout<<endl<<"Just one coefficient:"<<endl;
	cout<<myptri.get_coeff(n/2, n/4)<<endl<<endl;
	return 0;
}

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

(defn pascal [n]
  (let [newrow (fn newrow [lst ret]
                   (if lst
                       (recur (rest lst)
                              (conj ret (+ (first lst) (or (second lst) 0))))
                       ret))
        genrow (fn genrow [n lst]
                   (when (< 0 n)
                     (do (println lst)
                         (recur (dec n) (conj (newrow lst []) 1)))))]
    (genrow n [1])))
(pascal 4)

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:

(defn nextrow [row]
  (vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] )))

(defn pascal [n]
  (assert (and (integer? n) (pos? n)))
  (let [triangle (take n (iterate nextrow [1]))]
    (doseq [row triangle]
      (println row))))

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

(def pascal
  (iterate
    (fn [prev-row]
      (->>
        (concat [[(first prev-row)]] (partition 2 1 prev-row) [[(last prev-row)]])
        (map (partial apply +) ,,,)))
     [1]))

Another short version which returns an infinite pascal triangle as a list, using the iterate function.

(def pascal 
  (iterate #(concat [1] 
                    (map + % (rest %)) 
                    [1]) 
           [1]))

One can then get the first n rows using the take function

(take 10 pascal) ; returns a list of the first 10 pascal rows

Also, one can retrieve the nth row using the nth function

(nth pascal 10) ;returns the nth row

CoffeeScript

This version assumes n is an integer and n >= 1. It efficiently computes binomial coefficients.

pascal = (n) ->
  width = 6
  for r in [1..n]
    s = ws (width/2) * (n-r) # center row
    output = (n) -> s += pad width, n
    cell = 1
    output cell
    # Compute binomial coefficients as you go
    # across the row.
    for c in [1...r]
      cell *= (r-c) / c
      output cell
    console.log s

ws = (n) ->
  s = ''
  s += ' ' for i in [0...n]
  s

pad = (cnt, n) ->
  s = n.toString()
  # There is probably a better way to do this.
  cnt -= s.length
  right = Math.floor(cnt / 2)
  left = cnt - right
  ws(left) + s + ws(right)

pascal(7)
Output:
> coffee pascal.coffee 
                     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  

Commodore 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

Output:

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.

Common Lisp

To evaluate, call (pascal n). For n < 1, it simply returns nil.

(defun pascal (n)
  (genrow n '(1)))

(defun genrow (n l)
  (when (plusp n)
    (print l)
    (genrow (1- n) (cons 1 (newrow l)))))

(defun newrow (l)
  (if (null (rest l))
      '(1)
      (cons (+ (first l) (second l))
            (newrow (rest l)))))

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

(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))

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.

(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)))

For example:

(print-pascal-triangle 4)
   1     
  1 1    
 1 2 1   
1 3 3 1
(print-pascal-triangle 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

Component Pascal

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.
Execute: ^Q PascalTriangle.Do 0 1 2 3 4 5 6 7 8 9 10 11 12~
Output:
 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

D

Less functional Version

int[][] pascalsTriangle(in int rows) pure nothrow {
    auto tri = new int[][rows];
    foreach (r; 0 .. rows) {
        int v = 1;
        foreach (c; 0 .. r+1) {
            tri[r] ~= v;
            v = (v * (r - c)) / (c + 1);
        }
    }
    return tri;
}

void main() {
    immutable t = pascalsTriangle(10);
    assert(t == [[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]]);
}

More functional Version

import std.stdio, std.algorithm, std.range;

auto pascal() pure nothrow {
    return [1].recurrence!q{ zip(a[n - 1] ~ 0, 0 ~ a[n - 1])
                             .map!q{ a[0] + a[1] }
                             .array };
}

void main() {
    pascal.take(5).writeln;
}
Output:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]

Alternative Version

There is similarity between Pascal's triangle and Sierpinski triangle. 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).

import std.stdio, std.string, std.array, std.format;

string Pascal(alias dg, T, T initValue)(int n) {
    string output;

    void append(in T[] l) {
        output ~= " ".replicate((n - l.length + 1) * 2);
        foreach (e; l)
            output ~= format("%4s", format("%4s", e));
        output ~= "\n";
    }

    if (n > 0) {
        T[][] lines = [[initValue]];
        append(lines[0]);
        foreach (i; 1 .. n) {
            lines ~= lines[i - 1] ~ initValue; // length + 1
            foreach (int j; 1 .. lines[i-1].length)
                lines[i][j] = dg(lines[i-1][j], lines[i-1][j-1]);
            append(lines[i]);
        }
    }
    return output;
}

string delegate(int n) genericPascal(alias dg, T, T initValue)() {
    mixin Pascal!(dg, T, initValue);
    return &Pascal;
}

void main() {
    auto pascal = genericPascal!((int a, int b) => a + b, int, 1)();
    static char xor(char a, char b) { return a == b ? '_' : '*'; }
    auto sierpinski = genericPascal!(xor, char, '*')();

    foreach (i; [1, 5, 9])
        writef(pascal(i));
    // an order 4 sierpinski triangle is a 2^4 lines generic
    // Pascal triangle with xor operation
    foreach (i; [16])
        writef(sierpinski(i));
}
Output:
     1
             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   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
       1   7  21  35  35  21   7   1
     1   8  28  56  70  56  28   8   1
                                   *
                                 *   *
                               *   _   *
                             *   *   *   *
                           *   _   _   _   *
                         *   *   _   _   *   *
                       *   _   *   _   *   _   *
                     *   *   *   *   *   *   *   *
                   *   _   _   _   _   _   _   _   *
                 *   *   _   _   _   _   _   _   *   *
               *   _   *   _   _   _   _   _   *   _   *
             *   *   *   *   _   _   _   _   *   *   *   *
           *   _   _   _   *   _   _   _   *   _   _   _   *
         *   *   _   _   *   *   _   _   *   *   _   _   *   *
       *   _   *   _   *   _   *   _   *   _   *   _   *   _   *
     *   *   *   *   *   *   *   *   *   *   *   *   *   *   *   *

Dart

import 'dart:io';

pascal(n) {
  if(n<=0) print("Not defined");
  
  else if(n==1) print(1);
  
  else {
    List<List<int>> matrix = new List<List<int>>();
    matrix.add(new List<int>());
    matrix.add(new List<int>());
    matrix[0].add(1);
    matrix[1].add(1);
    matrix[1].add(1);
    for (var i = 2; i < n; i++) {
      List<int> list = new List<int>();
      list.add(1);
      for (var j = 1; j<i; j++) {
        list.add(matrix[i-1][j-1]+matrix[i-1][j]);
      }
      list.add(1);
      matrix.add(list);
    }
    for(var i=0; i<n; i++) {
      for(var j=0; j<=i; j++) {
        stdout.write(matrix[i][j]);
        stdout.write(' ');
      }
      stdout.write('\n');
    }
  }
}

void main() {
  pascal(0);
  pascal(1);
  pascal(3);
  pascal(6);
}

Delphi

program PascalsTriangle;

procedure Pascal(r:Integer);
var
  i, c, k:Integer;
begin
  for i := 0 to r - 1 do
  begin
    c := 1;
    for k := 0 to i do
    begin
      Write(c:3);
      c := c * (i - k) div (k + 1);
    end;
    Writeln;
  end;
end;

begin
  Pascal(9);
end.

DWScript

Doesn't print anything for negative or null values.

procedure Pascal(r : Integer);
var
   i, c, k : Integer;
begin
   for i:=0 to r-1 do begin
      c:=1;
      for k:=0 to i do begin
         Print(Format('%4d', [c]));
         c:=(c*(i-k)) div (k+1);
      end;
      PrintLn('');
   end;
end;

Pascal(9);
Output:
   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

E

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.

def pascalsTriangle(n, out) {
    def row := [].diverge(int)
    out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>")
    for y in 1..n {
        out.print("<tr>")
        row.push(1)
        def skip := n - y
        if (skip > 0) {
            out.print(`<td colspan="$skip"></td>`)
        }
        for x => v in row {
            out.print(`<td>$v</td><td></td>`)
        }
        for i in (1..!y).descending() {
            row[i] += row[i - 1]
        }
        out.println("</tr>")
    }
    out.print("</table>")
}
def out := <file:triangle.html>.textWriter()
try {
    pascalsTriangle(15, out)
} finally {
    out.close()
}
makeCommand("yourFavoriteWebBrowser")("triangle.html")

EasyLang

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

Eiffel

note
	description    : "Prints pascal's triangle"
	output         : "[
    			   Per requirements of the RosettaCode example, execution will print the first n rows of pascal's triangle
    			  ]"
	date           : "19 December 2013"
	authors        : "Sandro Meier", "Roman Brunner"
	revision       : "1.0"
	libraries      : "Relies on HASH_TABLE from EIFFEL_BASE library"
	implementation : "[
			   Recursive implementation to calculate the n'th row.
			 ]"
	warning        : "[
				Will not work for large n's (INTEGER_32)
		         ]"

class
	APPLICATION

inherit
	ARGUMENTS

create
	make

feature {NONE} -- Initialization

	make
		local
			n:INTEGER
		do
			create {HASH_TABLE[ARRAY[INTEGER],INTEGER]}pascal_lines.make (n) --create the hash_table object
			io.new_line
			n:=25
			draw(n)
		end
feature
	line(n:INTEGER):ARRAY[INTEGER]
		--Calculates the n'th line
	local
		upper_line:ARRAY[INTEGER]
		i:INTEGER
	do
		if	n=1 then	--trivial case first line
			create Result.make_filled (0, 1, n+2)
			Result.put (0, 1)
			Result.put (1, 2)
			Result.put (0, 3)
		elseif pascal_lines.has (n) then	--checks if the result was already calculated
			Result := pascal_lines.at (n)
		else	--calculates the n'th line recursively
			create Result.make_filled(0,1,n+2) --for caluclation purposes add a 0 at the beginning of each line
			Result.put (0, 1)
			upper_line:=line(n-1)
			from
				i:=1
			until
				i>upper_line.count-1
			loop
				Result.put(upper_line[i]+upper_line[i+1],i+1)
				i:=i+1
			end
			Result.put (0, n+2)	--for caluclation purposes add a 0 at the end of each line
			pascal_lines.put (Result, n)
		end
	end

	draw(n:INTEGER)
		--draw n lines of pascal's triangle
	local
		space_string:STRING
		width, i:INTEGER

	do
		space_string:=" "		--question of design: add space_string at the beginning of each line
		width:=line(n).count
		space_string.multiply (width)
		from
			i:=1
		until
			i>n
		loop
			space_string.remove_tail (1)
			io.put_string (space_string)
			across line(i) as c
			loop
				if
					c.item/=0
				then
					io.put_string (c.item.out+" ")
				end
			end
			io.new_line
			i:=i+1
		end
	end

feature --Access
	pascal_lines:HASH_TABLE[ARRAY[INTEGER],INTEGER]
		--Contains all already calculated lines
end

Elixir

defmodule Pascal do
  def triangle(n), do: triangle(n,[1])
  
  def triangle(0,list), do: list
  def triangle(n,list) do
    IO.inspect list
    new_list = Enum.zip([0]++list, list++[0]) |> Enum.map(fn {a,b} -> a+b end)
    triangle(n-1,new_list)
  end
end

Pascal.triangle(8)
Output:
[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]

Emacs Lisp

Using mapcar and append, returing a list of rows

(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)))))
Output:

Call the function from the REPL, IELM:

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

Translation from Pascal

(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))))
Output:

From the REPL:

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 

Returning a string

Same as the translation from Pascal, but now returning a string.

(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))
Output:

Now, since this one returns a string, it is possible to insert the result in the current buffer:

(insert (pascal 6))
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 

Erlang

-import(lists).
-export([pascal/1]).

pascal(1)-> [[1]];
pascal(N) ->
    L = pascal(N-1),
    [H|_] = L,
    [lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].
Output:
  Eshell V5.5.5  (abort with ^G)
  1> pascal:pascal(5).
  [[1,4,6,4,1],[1,3,3,1],[1,2,1],[1,1],[1]]

ERRE

PROGRAM PASCAL_TRIANGLE

PROCEDURE PASCAL(R%)
  LOCAL I%,C%,K%
    FOR I%=0 TO R%-1 DO
      C%=1
      FOR K%=0 TO I% DO
        WRITE("###";C%;)
        C%=(C%*(I%-K%)) DIV (K%+1)
      END FOR
      PRINT
   END FOR
END PROCEDURE

BEGIN
  PASCAL(9)
END PROGRAM

Output:

  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

Euphoria

Summing from Previous Rows

sequence row
row = {}
for m = 1 to 10 do
    row = row & 1
    for n = length(row)-1 to 2 by -1 do
        row[n] += row[n-1]
    end for
    print(1,row)
    puts(1,'\n')
end for
Output:
 {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}

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 LAMBDA: The ultimate Excel worksheet function)

PASCAL
=LAMBDA(n,
    BINCOEFF(n - 1)(
        SEQUENCE(1, n, 0, 1)
    )
)


BINCOEFF
=LAMBDA(n,
    LAMBDA(k,
        QUOTIENT(FACT(n), FACT(k) * FACT(n - k))
    )
)
Output:
fx =PASCAL(A2)
A B C D E F G H I J K
1 Row number PASCAL's TRIANGLE
2 1 1
3 2 1 1
4 3 1 2 1
5 4 1 3 3 1
6 5 1 4 6 4 1
7 6 1 5 10 10 5 1
8 7 1 6 15 20 15 6 1
9 8 1 7 21 35 35 21 7 1
10 9 1 8 28 56 70 56 28 8 1
11 10 1 9 36 84 126 126 84 36 9 1

Or defining the whole triangle as a single grid, by binding the name TRIANGLE to an additional lambda:

TRIANGLE
=LAMBDA(n,
    LET(
        ixs, SEQUENCE(n, n, 0, 1),
        x, MOD(ixs, n),
        y, QUOTIENT(ixs, n),
        IF(x <= y,
            BINCOEFF(y)(x),
            ""
        )
    )
)
Output:
fx =TRIANGLE(10)
A B C D E F G H I J K
1 PASCAL's TRIANGLE
2 1
3 1 1
4 1 2 1
5 1 3 3 1
6 1 4 6 4 1
7 1 5 10 10 5 1
8 1 6 15 20 15 6 1
9 1 7 21 35 35 21 7 1
10 1 8 28 56 70 56 28 8 1
11 1 9 36 84 126 126 84 36 9 1

F#

let rec nextrow l =
    match l with
    | []      -> []
    | h :: [] -> [1]
    | h :: t  -> h + t.Head :: nextrow t
   
let pascalTri n = List.scan(fun l i -> 1 :: nextrow l) [1] [1 .. n]

for row in pascalTri(10) do
    for i in row do
        printf "%s" (i.ToString() + ", ")
    printfn "%s" "\n"

Factor

This implementation works by summing the previous line content. Result for n < 1 is the same as for n == 1.

USING: grouping kernel math sequences ;

: (pascal) ( seq -- newseq )
    dup last 0 prefix 0 suffix 2 <clumps> [ sum ] map suffix ;

: pascal ( n -- seq )
    1 - { { 1 } } swap [ (pascal) ] times ;

It works as:

5 pascal .
{ { 1 } { 1 1 } { 1 2 1 } { 1 3 3 1 } { 1 4 6 4 1 } }

Fantom

class Main
{
  Int[] next_row (Int[] row)
  {
    new_row := [1]
    (row.size-1).times |i|
    {
      new_row.add (row[i] + row[i+1])
    }
    new_row.add (1)

    return new_row
  }

  Void print_pascal (Int n)  // no output for n <= 0
  {
    current_row := [1]
    n.times 
    {
      echo (current_row.join(" "))
      current_row = next_row (current_row)
    }
  }

  Void main ()
  {
    print_pascal (10)
  }
}

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)
Output:
=    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

Forth

: init ( n -- )
  here swap cells erase  1 here ! ;
: .line ( n -- )
  cr here swap 0 do dup @ . cell+ loop drop ;
: next ( n -- )
  here swap 1- cells here + do
    i @ i cell+ +!
  -1 cells +loop ;
: pascal ( n -- )
      dup init   1  .line
  1 ?do i next i 1+ .line loop ;

This is a bit more efficient.

Translation of: C
: PascTriangle
  cr dup 0
  ?do
     1 over 1- i - 2* spaces i 1+ 0 ?do dup 4 .r j i - * i 1+ / loop cr drop
  loop drop
;

13 PascTriangle

Fortran

Works with: Fortran version 90 and later

Prints nothing for n<=0. Output formatting breaks down for n>20

PROGRAM Pascals_Triangle

  CALL Print_Triangle(8)

END PROGRAM Pascals_Triangle

SUBROUTINE Print_Triangle(n)

  IMPLICIT NONE
  INTEGER, INTENT(IN) :: n
  INTEGER :: c, i, j, k, spaces

  DO i = 0, n-1
     c = 1
     spaces = 3 * (n - 1 - i)
     DO j = 1, spaces
        WRITE(*,"(A)", ADVANCE="NO") " "
     END DO
     DO k = 0, i
        WRITE(*,"(I6)", ADVANCE="NO") c
        c = c * (i - k) / (k + 1)
     END DO
     WRITE(*,*)
  END DO

END SUBROUTINE Print_Triangle

FreeBASIC

' FB 1.05.0 Win64

Sub pascalTriangle(n As UInteger)
  If n = 0 Then Return
  Dim prevRow(1 To n) As UInteger
  Dim currRow(1 To n) As UInteger
  Dim start(1 To n) As UInteger  ''stores starting column for each row
  start(n) = 1
  For i As Integer = n - 1 To 1 Step -1
    start(i) = start(i + 1) + 3
  Next
  prevRow(1) = 1
  Print Tab(start(1));
  Print 1U
  For i As UInteger = 2 To n
    For j As UInteger = 1 To i
      If j = 1 Then
        Print Tab(start(i)); "1";
        currRow(1) = 1
      ElseIf j = i Then
        Print "     1"
        currRow(i) = 1
      Else
        currRow(j) = prevRow(j - 1) + prevRow(j)
        Print Using "######"; currRow(j); "    "; 
      End If
    Next j 
    For j As UInteger = 1 To i
      prevRow(j) = currRow(j)
    Next j
  Next i
End Sub
 
pascalTriangle(14)  
Print
Print "Press any key to quit"
Sleep
Output:
                                       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

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.

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]
Output:
                    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   

FunL

Summing from Previous Rows

Translation of: Scala
import lists.zip

def
  pascal( 1 ) = [1]
  pascal( n ) = [1] + map( (a, b) -> a + b, zip(pascal(n-1), pascal(n-1).tail()) ) + [1]

Combinations

Translation of: Haskell
import integers.choose

def pascal( n ) = [choose( n - 1, k ) | k <- 0..n-1]

Pascal's Triangle

def triangle( height ) =
  width = max( map(a -> a.toString().length(), pascal(height)) )

  if 2|width
    width++

  for n <- 1..height
    print( ' '*((width + 1)\2)*(height - n) )
    println( map(a -> format('%' + width + 'd ', a), pascal(n)).mkString() )

triangle( 10 )
Output:
                    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

Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Solution

Test case

GAP

Pascal := function(n)
	local i, v;
	v := [1];
	for i in [1 .. n] do
		Display(v);
		v := Concatenation([0], v) + Concatenation(v, [0]);
	od;
end;

Pascal(9);  
# [ 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 ]

Go

No output for n < 1. Otherwise, output formatted left justified.

package main

import "fmt"

func printTriangle(n int) {
    // degenerate cases
    if n <= 0 {
        return
    }
    fmt.Println(1)
    if n == 1 {
        return
    }
    // iterate over rows, zero based
    a := make([]int, (n+1)/2)
    a[0] = 1
    for row, middle := 1, 0; row < n; row++ {
        // generate new row
        even := row&1 == 0
        if even {
            a[middle+1] = a[middle] * 2
        }
        for i := middle; i > 0; i-- {
            a[i] += a[i-1]
        }
        // print row
        for i := 0; i <= middle; i++ {
            fmt.Print(a[i], " ")
        }
        if even {
            middle++
        }
        for i := middle; i >= 0; i-- {
            fmt.Print(a[i], " ")
        }
        fmt.Println("")
    }
}

func main() {
    printTriangle(4)
}

Output:

1
1 1
1 2 1
1 3 3 1

Groovy

Recursive

In the spirit of the Haskell "think in whole lists" solution here is a list-driven, minimalist solution:

def pascal
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }

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:

def count = 15
(1..count).each { n ->
    printf ("%2d:", n); (0..(count-n)).each { print "    " }; pascal(n).each{ printf("%6d  ", it) }; println ""
}
Output:
 1:                                                                 1  
 2:                                                             1       1  
 3:                                                         1       2       1  
 4:                                                     1       3       3       1  
 5:                                                 1       4       6       4       1  
 6:                                             1       5      10      10       5       1  
 7:                                         1       6      15      20      15       6       1  
 8:                                     1       7      21      35      35      21       7       1  
 9:                                 1       8      28      56      70      56      28       8       1  
10:                             1       9      36      84     126     126      84      36       9       1  
11:                         1      10      45     120     210     252     210     120      45      10       1  
12:                     1      11      55     165     330     462     462     330     165      55      11       1  
13:                 1      12      66     220     495     792     924     792     495     220      66      12       1  
14:             1      13      78     286     715    1287    1716    1716    1287     715     286      78      13       1  
15:         1      14      91     364    1001    2002    3003    3432    3003    2002    1001     364      91      14       1  

GW-BASIC

10 INPUT "Number of rows? ",R
20 FOR I=0 TO R-1
30 C=1
40 FOR K=0 TO I
50 PRINT USING "####";C;
60 C=C*(I-K)/(K+1)
70 NEXT
80 PRINT
90 NEXT

Output:

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

Haskell

An approach using the "think in whole lists" principle: Each row in the triangle can be calculated from the previous row by adding a shifted version of itself to it, keeping the ones at the ends. The Prelude function zipWith can be used to add two lists, but it won't keep the old values when one list is shorter. So we need a similar function

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

Now we can shift a list and add it to itself, extending it by keeping the ends:

extendWith f [] = []
extendWith f xs@(x:ys) = x : zapWith f xs ys

And for the whole (infinite) triangle, we just iterate this operation, starting with the first row:

pascal = iterate (extendWith (+)) [1]

For the first n rows, we just take the first n elements from this list, as in

*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]]

A shorter approach, plagiarized from [2]

-- generate next row from current row
nextRow row = zipWith (+) ([0] ++ row) (row ++ [0])

-- returns the first n rows
pascal = iterate nextRow [1]

Alternatively, using list comprehensions:

pascal :: [[Integer]]
pascal =
  (1 : [ 0 | _ <- head pascal])
  : [zipWith (+) (0:row) row | row <- pascal]
*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]]

With binomial coefficients:

fac = product . enumFromTo 1

binCoef n k = fac n `div` (fac k * fac (n - k))

pascal = ((fmap . binCoef) <*> enumFromTo 0) . pred

Example:

*Main> putStr $ unlines $ map unwords $ map (map show) $ pascal 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

HicEst

   CALL Pascal(30)

SUBROUTINE Pascal(rows)
   CHARACTER fmt*6
   WRITE(Text=fmt, Format='"i", i5.5') 1+rows/4

   DO row = 0, rows-1
     n = 1
     DO k = 0, row
       col = rows*(rows-row+2*k)/4
       WRITE(Row=row+1, Column=col, F=fmt) n
       n = n * (row - k) / (k + 1)
     ENDDO
   ENDDO
END

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

link math
 
procedure main(A)
every n := !A do  {    # for each command line argument 
   n := integer(\n) | &null
   pascal(n)
   }
end
 
procedure pascal(n)		#: Pascal triangle
   /n := 16
   write("width=", n, " height=", n)	# carpet header
   fw := *(2 ^ n)+1
   every i := 0 to n - 1 do {
      writes(repl(" ",fw*(n-i)/2))
      every j := 0 to n - 1 do
         writes(center(binocoef(i, j),fw) | break)
      write()
      }
end

math provides binocoef math provides the original version of pascal

Sample output:

->pascal 1 4 8
width=1 height=1
 1 
width=4 height=4
       1 
     1  1 
    1  2  1 
  1  3  3  1 
width=8 height=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  
->

IDL

Pro Pascal, n
;n is the number of lines of the triangle to be displayed
 r=[1]
 print, r
  for i=0, (n-2) do begin
    pascalrow,r
  endfor
End

Pro PascalRow, r
  for i=0,(n_elements(r)-2) do begin 
    r[i]=r[i]+r[i+1]
  endfor
r= [1, r]
print, r

End

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
Output:
                                         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

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

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
   ([: ":@-.&0"1 !~/~)@i. 5
1        
1 1      
1 2 1    
1 3 3 1  
1 4 6 4 1
   (-@|. |."_1 [: ":@-.&0"1 !~/~)@i. 5
     1    
    1 1   
   1 2 1  
  1 3 3 1 
 1 4 6 4 1

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:

   (|."_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

Also... when we mix positive and negative numbers it stops being a triangle:

   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


See the talk page for explanation of earlier version

See also Pascal matrix generation and Sierpinski triangle.

Java

Summing from Previous Rows

Works with: Java version 1.5+
import java.util.ArrayList;
...//class definition, etc.
public static void genPyrN(int rows){
	if(rows < 0) return;
	//save the last row here
	ArrayList<Integer> last = new ArrayList<Integer>();
	last.add(1);
	System.out.println(last);
	for(int i= 1;i <= rows;++i){
		//work on the next row
		ArrayList<Integer> thisRow= new ArrayList<Integer>();
		thisRow.add(last.get(0)); //beginning
		for(int j= 1;j < i;++j){//loop the number of elements in this row
			//sum from the last row
			thisRow.add(last.get(j - 1) + last.get(j));
		}
		thisRow.add(last.get(0)); //end
		last= thisRow;//save this row
		System.out.println(thisRow);
	}
}

Combinations

This method is limited to 21 rows because of the limits of long. Calling pas with an argument of 22 or above will cause intermediate math to wrap around and give false answers.

public class Pas{
	public static void main(String[] args){
		//usage
		pas(20);
	}

	public static void pas(int rows){
		for(int i = 0; i < rows; i++){
			for(int j = 0; j <= i; j++){
				System.out.print(ncr(i, j) + " ");
			}
			System.out.println();
		}
	}

	public static long ncr(int n, int r){
		return fact(n) / (fact(r) * fact(n - r));
	}

	public static long fact(int n){
		long ans = 1;
		for(int i = 2; i <= n; i++){
			ans *= i;
		}
		return ans;
	}
}

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.

public class Pascal {
	private static void printPascalLine (int n) {
		if (n < 1)
			return;
		int m = 1;
		System.out.print("1 ");
		for (int j=1; j<n; j++) {
			m = m * (n-j)/j;
			System.out.print(m);
			System.out.print(" ");
		}
		System.out.println();
	}
	
	public static void printPascal (int nRows) {
		for(int i=1; i<=nRows; i++)
			printPascalLine(i);
	}
}

JavaScript

ES5

Imperative

Works with: SpiderMonkey
Works with: V8
// Pascal's triangle object
function pascalTriangle (rows) {

	// Number of rows the triangle contains
	this.rows = rows;

	// The 2D array holding the rows of the triangle
	this.triangle = new Array();
	for (var r = 0; r < rows; r++) {
		this.triangle[r] = new Array();
		for (var i = 0; i <= r; i++) {
			if (i == 0 || i == r)
				this.triangle[r][i] = 1;
			else
				this.triangle[r][i] = this.triangle[r-1][i-1]+this.triangle[r-1][i];
		}
	}

	// Method to print the triangle
	this.print = function(base) {
		if (!base)
			base = 10;

		// Private method to calculate digits in number
		var digits = function(n,b) {
			var d = 0;
			while (n >= 1) {
				d++;
				n /= b;
			}
			return d;
		}

		// Calculate max spaces needed
		var spacing = digits(this.triangle[this.rows-1][Math.round(this.rows/2)],base);

		// Private method to add spacing between numbers
		var insertSpaces = function(s) {
			var buf = "";
			while (s > 0) {
				s--;
				buf += " ";
			}
			return buf;
		}

		// Print the triangle line by line
		for (var r = 0; r < this.triangle.length; r++) {
			var l = "";
			for (var s = 0; s < Math.round(this.rows-1-r); s++) {
				l += insertSpaces(spacing);
			}
			for (var i = 0; i < this.triangle[r].length; i++) {
				if (i != 0)
					l += insertSpaces(spacing-Math.ceil(digits(this.triangle[r][i],base)/2));
				l += this.triangle[r][i].toString(base);
				if (i < this.triangle[r].length-1)
					l += insertSpaces(spacing-Math.floor(digits(this.triangle[r][i],base)/2));
			}
			print(l);
		}
	}

}

// Display 4 row triangle in base 10
var tri = new pascalTriangle(4);
tri.print();
// Display 8 row triangle in base 16
tri = new pascalTriangle(8);
tri.print(16);

Output:

$ d8 pascal.js 
   1
  1 1
 1 2 1
1 3 3 1
              1
            1   1
          1   2   1
        1   3   3   1
      1   4   6   4   1
    1   5   a   a   5   1
  1   6   f   14  f   6   1
1   7   15  23  23  15  7   1

Functional

Translation of: Haskell
(function (n) {
    'use strict';

    // PASCAL TRIANGLE --------------------------------------------------------

    // pascal :: Int -> [[Int]]
    function pascal(n) {
        return foldl(function (a) {
            var xs = a.slice(-1)[0]; // Previous row
            return append(a, [zipWith(
                function (a, b) {
                    return a + b;
                },
                append([0], xs),
                append(xs, [0])
            )]);
        }, [
            [1] // Initial seed row
        ], enumFromTo(1, n - 1));
    };


    // GENERIC FUNCTIONS ------------------------------------------------------

    // (++) :: [a] -> [a] -> [a]
    function append(xs, ys) {
        return xs.concat(ys);
    };

    // enumFromTo :: Int -> Int -> [Int]
    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 Array.from({
            length: min(xs.length, ys.length)
        }, function (_, i) {
            return f(xs[i], ys[i]);
        });
    };

    // TEST and FORMAT --------------------------------------------------------
    var lstTriangle = pascal(n);

    // [[a]] -> bool -> s -> s
    function wikiTable(lstRows, blnHeaderRow, strStyle) {
        return '{| class="wikitable" ' + (strStyle ? 'style="' + strStyle +
                '"' : '') + lstRows.map(function (lstRow, iRow) {
                var strDelim = blnHeaderRow && !iRow ? '!' : '|';
                return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) {
                        return typeof v === 'undefined' ? ' ' : v;
                    })
                    .join(' ' + strDelim + strDelim + ' ');
            })
            .join('') + '\n|}';
    }

    var lstLastLine = lstTriangle.slice(-1)[0],
        lngBase = lstLastLine.length * 2 - 1,
        nWidth = lstLastLine.reduce(function (a, x) {
            var d = x.toString()
                .length;
            return d > a ? d : a;
        }, 1) * lngBase;

    return [wikiTable(lstTriangle.map(function (lst) {
            return lst.join(';;')
                .split(';');
        })
        .map(function (line, i) {
            var lstPad = Array((lngBase - line.length) / 2);
            return lstPad.concat(line)
                .concat(lstPad);
        }), false, 'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
        'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n');
})(7);
Output:
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]]

ES6

(() => {
    "use strict";

    // ---------------- PASCAL'S TRIANGLE ----------------

    // pascal :: Generator [[Int]]
    const pascal = () =>
        iterate(
            xs => zipWith(
                a => b => a + b
            )(
                [0, ...xs]
            )(
                [...xs, 0]
            )
        )([1]);


    // ---------------------- TEST -----------------------
    // main :: IO ()
    const main = () =>
        showPascal(
            take(10)(
                pascal()
            )
        );


    // showPascal :: [[Int]] -> String
    const showPascal = xs => {
        const w = last(xs).join("   ").length;

        return xs.map(
            ys => center(w)(" ")(ys.join("   "))
        )
        .join("\n");
    };


    // ---------------- GENERIC FUNCTIONS ----------------

    // 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();
})();
Output:
                      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

Recursive

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)
Output:
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

Recursive - memoized

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)

jq

Works with: jq version 1.4

pascal(n) as defined here produces a stream of n arrays, each corresponding to a row of the Pascal triangle. The implementation avoids any arithmetic except addition.

# pascal(n) for n>=0; pascal(0) emits an empty stream.
def pascal(n):
  def _pascal:  # input: the previous row
    . as $in
    | .,
      if length >= n then empty
      else
        reduce range(0;length-1) as $i
          ([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] | _pascal
      end;
  if n <= 0 then empty else [1] | _pascal end ;

Example:

pascal(5)
Output:
$ jq -c -n -f pascal_triangle.jq
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]

Using recurse/1

Here is an equivalent implementation that uses the built-in filter, recurse/1, instead of the inner function.

def pascal(n):
  if n <= 0 then empty
  else [1]
  | recurse( if length >= n then empty
             else . as $in 
             | reduce range(0;length-1) as $i
                 ([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1]
             end)
  end;

Julia

function pascal(n)
  if n<=0
   print("n has to have a positive value")
  end
  x=0
  while x<=n
   for a=0:x
    print(binomial(x,a)," ")
   end
   println("")
   x+=1
  end
end
pascal(5)
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 

Another solution using matrix exponentiation.

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
Output:
pascal(5)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Yet another solution using a static vector

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
Output:
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

K

pascal:{(x-1){+':x,0}\1}
pascal 6
(1
 1 1
 1 2 1
 1 3 3 1
 1 4 6 4 1
 1 5 10 10 5 1)

Kotlin

fun pas(rows: Int) {
    for (i in 0..rows - 1) {
        for (j in 0..i)
            print(ncr(i, j).toString() + " ")
        println()
    }
}

fun ncr(n: Int, r: Int) = fact(n) / (fact(r) * fact(n - r))

fun fact(n: Int) : Long {
    var ans = 1.toLong()
    for (i in 2..n)
        ans *= i
    return ans
}

fun main(args: Array<String>) = pas(args[0].toInt())

Lambdatalk

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

Liberty BASIC

input "How much rows would you like? "; n
dim a$(n)

for i=  0 to n
       c = 1
       o$ =""
       for k =0 to i
             o$ =o$ ; c; " "
             c =c *(i-k)/(k+1)
       next k
       a$(i)=o$
next i

maxLen = len(a$(n))
for i=  0 to n
    print space$((maxLen-len(a$(i)))/2);a$(i)
next i

end

Locomotive Basic

10 CLS
20 INPUT "Number of rows? ", rows:GOSUB 40
30 END
40 FOR i=0 TO rows-1
50 c=1
60 FOR k=0 TO i
70 PRINT USING "####";c;
80 c=c*(i-k)/(k+1)
90 NEXT
100 PRINT
110 NEXT
120 RETURN

Output:

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

to pascal :n
  if :n = 1 [output [1]]
  localmake "a pascal :n-1
  output (sentence first :a (map "sum butfirst :a butlast :a) last :a)
end

for [i 1 10] [print pascal :i]

Logtalk

Our implementation will have an object pascals with work done in the method triangle/2. We will be caching results for time efficiency at the cost of space efficiency,and the reset/0 method will flush that cache should it grow to be a problem. The resulting object looks like this:

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

Using the SWI-Prolog back-end:

?- 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|...], [...|...]|...].

?-

Lua

function nextrow(t)
  local ret = {}
  t[0], t[#t+1] = 0, 0
  for i = 1, #t do ret[i] = t[i-1] + t[i] end
  return ret
end

function triangle(n)
  t = {1}
  for i = 1, n do
    print(unpack(t))
    t = nextrow(t)
  end
end

Maple

f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1);

f(3);
   1
  1 1
 1 2 1

Mathematica/Wolfram Language

n=7;
Column[StringReplace[ToString /@ Replace[MatrixExp[SparseArray[
{Band[{2,1}] -> Range[n-1]},{n,n}]],{x__,0..}->{x},2] ,{"{"|"}"|","->" "}], Center]

A more graphical output with arrows would involve the plotting functionality with Graph[]:

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]

MATLAB / Octave

A matrix containing the pascal triangle can be obtained this way:

pascal(n);
>> pascal(6)
ans =

     1     1     1     1     1     1
     1     2     3     4     5     6
     1     3     6    10    15    21
     1     4    10    20    35    56
     1     5    15    35    70   126
     1     6    21    56   126   252

The binomial coefficients can be extracted from the Pascal triangle in this way:

  binomCoeff = diag(rot90(pascal(n)))',
>> for k=1:6,diag(rot90(pascal(k)))', end
ans =  1
ans =

   1   1

ans =

   1   2   1

ans =

   1   3   3   1

ans =

   1   4   6   4   1

ans =

    1    5   10   10    5    1

Another way to get a formated pascals triangle is to use the convolution method:

>>
x = [1  1] ;      
y = 1;                   
for k=8:-1:1
    fprintf(['%', num2str(k), 'c'], zeros(1,3)), 
    fprintf('%6d', y), fprintf('\n')             
   y = conv(y,x);                        
                                         
end

The result is:

>>

                          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

Maxima

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), " "));

display_pascal_triangle(6);
/* "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" */

Metafont

(The formatting starts to be less clear when numbers start to have more than two digits)

vardef bincoeff(expr n, k) =
save ?;
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor )
     / (1 for i=2 upto min(k, n-k): * i endfor); ?
enddef;

def pascaltr expr c =
  string s_;
  for i := 0 upto (c-1):
    s_ := "" for k=0 upto (c-i): & "  " endfor;
    s_ := s_ for k=0 upto i: & decimal(bincoeff(i,k))
             & "  " if bincoeff(i,k)<9: & " " fi endfor;
    message s_;
  endfor
enddef;

pascaltr(4);
end

Microsoft Small Basic

Translation of: GW-BASIC
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

Output:

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

Modula-2

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.

NetRexx

/* NetRexx */
options replace format comments java crossref symbols nobinary

numeric digits 1000 -- allow very large numbers
parse arg rows .
if rows = '' then rows = 11 -- default to 11 rows
printPascalTriangle(rows)
return

-- -----------------------------------------------------------------------------
method printPascalTriangle(rows = 11) public static
  lines = ''
  mx = (factorial(rows - 1) / factorial(rows % 2) / factorial(rows - 1 - rows % 2)).length() -- width of widest number

  loop row = 1 to rows
    n1 = 1.center(mx)
    line = n1
    loop col = 2 to row
      n2 = col - 1
      n1 = n1 * (row - n2) / n2
      line = line n1.center(mx)
      end col
    lines[row] = line.strip()
    end row

  -- display triangle
  ml = lines[rows].length() -- length of longest line
  loop row = 1 to rows
    say lines[row].centre(ml)
    end row

  return

-- -----------------------------------------------------------------------------
method factorial(n) public static
  fac = 1
  loop n_ = 2 to n
    fac = fac * n_
    end n_
  return fac /*calc. factorial*/
Output:
                    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

Nial

Like J

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

Using it

|loaddefs 'pascal.nial'
|pascal 5

Nim

import sequtils, strutils

proc printPascalTriangle(n: int) =
  ## Print a Pascal triangle.

  # Build the triangle.
  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)
Output:
                   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 

A more optimized solution that doesn't require importing, but produces, naturally, uglier output, would look like this:

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)
Output:
@[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]

OCaml

(* generate next row from current row *)
let next_row row =
  List.map2 (+) ([0] @ row) (row @ [0])

(* returns the first n rows *)
let pascal n =
  let rec loop i row =
    if i = n then []
    else row :: loop (i+1) (next_row row)
  in loop 0 [1]

Octave

function pascaltriangle(h)
  for i = 0:h-1
    for k = 0:h-i
      printf("  ");
    endfor
    for j = 0:i
      printf("%3d ", bincoeff(i, j));
    endfor
    printf("\n");
  endfor
endfunction

pascaltriangle(4);

Oforth

No result if n <= 0

: pascal(n)  [ 1 ] #[ dup println dup 0 + 0 rot + zipWith(#+) ] times(n) drop ;
Output:
10 pascal
[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]

Oz

declare
  fun {NextLine Xs}
     {List.zip 0|Xs {Append Xs [0]}
      fun {$ Left Right}
         Left + Right
      end}
  end

  fun {Triangle N}
     {List.take {Iterate [1] NextLine} N}
  end

  fun lazy {Iterate I F}
     I|{Iterate {F I} F}
  end

  %% Only works nicely for N =< 5.
  proc {PrintTriangle T}
     N = {Length T}
  in
     for
        Line in T
        Indent in N-1..0;~1
     do
        for _ in 1..Indent do {System.printInfo " "} end
        for L in Line do {System.printInfo L#" "} end
        {System.printInfo "\n"}
     end
  end
in
  {PrintTriangle {Triangle 5}}

For n = 0, prints nothing. For negative n, throws an exception.

PARI/GP

pascals_triangle(N)= {
my(row=[],prevrow=[]);
for(x=1,N,
    if(x>5,break(1));
         row=eval(Vec(Str(11^(x-1))));
         print(row));
prevrow=row;
for(y=6,N,
   for(p=2,#prevrow,
         row[p]=prevrow[p-1]+prevrow[p]);
         row=concat(row,1);
         prevrow=row;
         print(row);
     );
}

Pascal

Program PascalsTriangle(output);

procedure Pascal(r : Integer);
  var
    i, c, k : Integer;
  begin
    for i := 0 to r-1 do
    begin
      c := 1;
      for k := 0 to i do
      begin
        write(c:3);
        c := (c * (i-k)) div (k+1);
      end;
      writeln;
   end;
end;
 
begin
  Pascal(9)
end.

Output:

% ./PascalsTriangle 
  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

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

sub pascal {
  my $rows = shift;
  my @next = (1);
  for my $n (1 .. $rows) {
    print "@next\n";
    @next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1);
  }
}

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:

Library: ntheory
use ntheory qw/binomial/;
sub pascal {
  my $rows = shift;
  for my $n (0 .. $rows-1) {
    print join(" ", map { binomial($n,$_) } 0 .. $n), "\n";
  }
}

Here is a non-obvious version using bignum, which is limited to the first 23 rows because of the algorithm used:

use bignum;
sub pascal_line { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 }
sub pascal { print "@{[map -+-$_, pascal_line $_]}\n" for 0..$_[0]-1 }

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 Tartaglia's triangle

#!/usr/bin/perl
use strict;
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;
}


for (0..5) {print join ' ', tartaglia_row($_),"\n"}
print "\n\n";


print tartaglia(3,3),"\n";
my @third = tartaglia_row(5);
print "@third\n";

which output

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1


20
1 5 10 10 5 1

Phix

sequence row = {}
for m = 1 to 13 do
    row = row & 1
    for n=length(row)-1 to 2 by -1 do
        row[n] += row[n-1]
    end for
    printf(1,repeat(' ',(13-m)*2))
    for i=1 to length(row) do
        printf(1," %3d",row[i])
    end for
    puts(1,'\n')
end for
Output:
                           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

"Reflected" Pascal's triangle, it uses symmetry property to "mirror" second part. It determines even and odd strings. automatically.

PHP

<?php
 //Author Ivan Gavryshin @dcc0
function tre($n) {
  $ck=1;
  $kn=$n+1;
    
 if($kn%2==0) {
 $kn=$kn/2;
 $i=0;
  }
 else
  {

  $kn+=1;
  $kn=$kn/2;
  $i= 1;
}

 for ($k = 1; $k <= $kn-1; $k++) { 
   $ck = $ck/$k*($n-$k+1);
   $arr[] = $ck;
   echo  "+" . $ck ;
 
  }
 

if ($kn>1) {
  echo $arr[i];
  $arr=array_reverse($arr);
 for ($i; $i<= $kn-1; $i++) {
 echo  "+" . $arr[$i]  ;
     }
 
   }
 
 }
 //set amount of strings here
 while ($n<=20) {
 ++$n;
 echo tre($n);
 echo "<br/>";
}
 
 
?>

==PHP==

function pascalsTriangle($num){
	$c = 1;
	$triangle = Array();
	for($i=0;$i<=$num;$i++){
		$triangle[$i] = Array();
		if(!isset($triangle[$i-1])){
			$triangle[$i][] = $c;
		}else{
			for($j=0;$j<count($triangle[$i-1])+1;$j++){
				$triangle[$i][] = (isset($triangle[$i-1][$j-1]) && isset($triangle[$i-1][$j])) ? $triangle[$i-1][$j-1] + $triangle[$i-1][$j] : $c;
			}
		}
	}
	return $triangle;
}

$tria = pascalsTriangle(8);
foreach($tria as $val){
	foreach($val as $value){
		echo $value . ' ';
	}
	echo '<br>';
}
                                       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

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

PicoLisp

Translation of: C
(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) ) )

PL/I

declare (t, u)(40) fixed binary;
declare (i, n) fixed binary;

t,u = 0;
get (n);
if n <= 0 then return;

do n = 1 to n;
   u(1) = 1;
   do i = 1 to n;
      u(i+1) = t(i) + t(i+1);
   end;
   put skip edit ((u(i) do i = 1 to n)) (col(40-2*n), (n+1) f(4));
   t = u;
end;
                                        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

Potion

printpascal = (n) :
   if (n < 1) :
      1 print
      (1)
   . else :
      prev = printpascal(n - 1)
      prev append(0)
      curr = (1)
      n times (i):
         curr append(prev(i) + prev(i + 1))
      .
      "\n" print
      curr join(", ") print
      curr
   .
.

printpascal(read number integer)

PowerShell

$Infinity = 1
$NewNumbers = $null
$Numbers = $null
$Result = $null
$Number = $null
$Power = $args[0]

Write-Host $Power

For(
   $i=0;
   $i -lt $Infinity;
   $i++
   )
   {
    $Numbers = New-Object Object[] 1
    $Numbers[0] = $Power
   For(
      $k=0;
      $k -lt $NewNumbers.Length;
      $k++
      )
      {
       $Numbers = $Numbers + $NewNumbers[$k]
      }
   If(
     $i -eq 0
     )
     {
      $Numbers = $Numbers + $Power
     }
    $NewNumbers = New-Object Object[] 0
   Try
   {
   For(
      $j=0;
      $j -lt $Numbers.Length;
      $j++
      )
      {
       $Result = $Numbers[$j] + $Numbers[$j+1]
       $NewNumbers = $NewNumbers + $Result
      }
   }
   Catch [System.Management.Automation.RuntimeException]
   {
    Write-Warning "Value was too large for a Decimal. Script aborted."
    Break;
   }
   Foreach(
          $Number in $Numbers
          )
          {
          If(
            $Number.ToString() -eq "+unendlich"
            )
            {
             Write-Warning "Value was too large for a Decimal. Script aborted."
             Exit
            }
          }
    Write-Host $Numbers
    $Infinity++
   }

Save the above code to a .ps1 script file and start it by calling its name and providing N.

PS C:\> & '.\Pascals Triangle.ps1' 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
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

Prolog

Difference-lists are used to make quick append.

pascal(N) :-
	pascal(1, N, [1], [[1]|X]-X, L),
	maplist(my_format, L).

pascal(Max, Max, L, LC, LF) :-
	!,
	make_new_line(L, NL),
	append_dl(LC, [NL|X]-X, LF-[]).

pascal(N, Max, L, NC, LF) :-
	build_new_line(L, NL),
	append_dl(NC, [NL|X]-X, NC1),
	N1 is N+1,
	pascal(N1, Max, NL, NC1, LF).

build_new_line(L, R) :-
	build(L, 0, X-X, R).

build([], V, RC, RF) :-
	append_dl(RC, [V|Y]-Y, RF-[]).

build([H|T], V, RC, R) :-
	V1 is V+H,
	append_dl(RC, [V1|Y]-Y, RC1),
	build(T, H, RC1, R).

append_dl(X1-X2, X2-X3, X1-X3).

% to have a correct output !
my_format([H|T]) :-
	write(H),
	maplist(my_writef, T),
	nl.

my_writef(X) :-
	writef(' %5r', [X]).

Output :

 ?- pascal(15).
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
true.

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.

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% 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(_).
  • Output*:
?- pascal(5).
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]

PureBasic

Procedure pascaltriangle( n.i)
 
  For i=  0 To  n
       c = 1
       For k=0 To i
             Print(Str( c)+" ")
         c = c * (i-k)/(k+1);
        Next ;k
    PrintN(" "); nächste zeile
  Next ;i

EndProcedure
 
OpenConsole()
Parameter.i = Val(ProgramParameter(0))
pascaltriangle(Parameter);
Input()

Python

Procedural

def pascal(n):
   """Prints out n rows of Pascal's triangle.
   It returns False for failure and True for success."""
   row = [1]
   k = [0]
   for x in range(max(n,0)):
      print row
      row=[l+r for l,r in zip(row+k,k+row)]
   return n>=1

or by creating a scan function:

def scan(op, seq, it):
  a = []
  result = it
  a.append(it)
  for x in seq:
    result = op(result, x)
    a.append(result)
  return a

def pascal(n):
    def nextrow(row, x):
        return [l+r for l,r in zip(row+[0,],[0,]+row)]

    return scan(nextrow, range(n-1), [1,])

for row in pascal(4):
    print(row)

Functional

Deriving finite and non-finite lists of pascal rows from a simple nextPascal step function:

Works with: Python version 3.7
'''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()
Output:
             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

q

pascal:{(x-1){0+':x,0}\1}
pascal 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Qi

Translation of: Haskell
(define iterate
  _ _ 0 -> []
  F V N -> [V|(iterate F (F V) (1- N))])

(define next-row
  R -> (MAPCAR + [0|R] (append R [0])))

(define pascal
  N -> (iterate next-row [1] N))

Quackery

The behaviour of pascal for values less than 1 is the same as its behaviour for 1.

  [ 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
Output:
    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

R

Translation of: Octave
pascalTriangle <- function(h) {
  for(i in 0:(h-1)) {
    s <- ""
    for(k in 0:(h-i)) s <- paste(s, "  ", sep="")
    for(j in 0:i) {
      s <- paste(s, sprintf("%3d ", choose(i, j)), sep="")
    }
    print(s)
  }
}

Here's an R version:

pascalTriangle <- function(h) {
  lapply(0:h, function(i) choose(i, 0:i))
}

Racket

Iterative version by summing rows up to .

#lang racket

(define (pascal n)
  (define (next-row current-row)
    (map + (cons 0 current-row)
           (append current-row '(0))))
  (reverse
   (for/fold ([triangle '((1))])
             ([row (in-range 1 n)])
     (cons (next-row (first triangle)) triangle))))

Raku

(formerly Perl 6)

Works with: rakudo version 2015-10-03

using a lazy sequence generator

The following routine returns a lazy list of lines using the sequence operator (...). 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:

sub pascal {
    [1], { [0, |$_ Z+ |$_, 0] } ... *
}
 
.say for pascal[^10];

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 @ sigil to indicate that the sequence should cache its values for reuse, and use an explicit parameter $prev for variety:

constant @pascal = [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... *;
 
.say for @pascal[^10];

Since we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error.

recursive

Translation of: Haskell
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;

Non-positive inputs throw a multiple-dispatch error.

iterative

Translation of: Perl
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;

Non-positive inputs throw a type check error.

Output:
[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]

RapidQ

Summing from Previous Rows

Translation of: BASIC

The main difference to BASIC implementation is the output formatting. RapidQ does not support PRINT USING. Instead, function FORMAT$() is used. TAB() is not supported, so SPACE$() was used instead.

Another difference is that in RapidQ, DIM does not clear array values to zero. But if dimensioning is done with DEF..., you can give the initial values in curly braces. If less values are given than there are elements in the array, the remaining positions are initialized to zero. RapidQ does not require simple variables to be declared before use.

DEFINT values(100) = {0,1}

INPUT "Number of rows: "; nrows
PRINT SPACE$((nrows)*3);"  1"
FOR row = 2 TO nrows
    PRINT SPACE$((nrows-row)*3+1);
    FOR i = row TO 1 STEP -1
        values(i) = values(i) + values(i-1)
        PRINT FORMAT$("%5d ", values(i));
    NEXT i
    PRINT
NEXT row

Using binary coefficients

Translation of: BASIC
INPUT "Number of rows: "; nrows
FOR row = 0 TO nrows-1
    c = 1
    PRINT SPACE$((nrows-row)*3);
    FOR i = 0 TO row
        PRINT FORMAT$("%5d ", c);
        c = c * (row - i) / (i+1)
    NEXT i
    PRINT
NEXT row

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

Output:

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

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

REXX

There is no practical limit for this REXX version, triangles up to 46 rows have been generated (without wrapping) in a screen window with a width of 620 characters.

If the number (of rows) specified is negative,   the output is written to a (disk) file instead.   Triangles with over a   1,000   rows have been easily created.
The output file created (that is written to disk) is named     PASCALS.n     where   n   is the absolute value of the number entered.


Note:   Pascal's triangle is also known as:

  •   Khayyam's triangle
  •   Khayyam─Pascal's triangle
  •   Tartaglia's triangle
  •   Yang Hui's triangle
/*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                 /*Not specified?  Then use the default.*/
n= abs(nn)                                       /*N  is the number of rows in triangle.*/
w= length( !(n-1)  %  !(n%2)  %  !(n - 1 - n%2)) /*W:  the width of biggest integer.    */
ww= (n-1) * (W + 1)   +   1                      /*WW:  "    "    " triangle's last row.*/
@.= 1;      $.= @.;          unity= right(1, w)  /*defaults rows & lines; aligned unity.*/
                                                 /* [↓]  build rows of Pascals' triangle*/
        do    r=1  for n;              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*/                           /* [↑]    C  is the column being built.*/
        if r\==1  then $.r= $.r  unity           /*for  rows≥2,  append a trailing  "1".*/
        end      /*r*/                           /* [↑]    R  is the  row   being built.*/
                                                 /* [↑]  WIDTH: for nicely looking line.*/
     do r=1  for n;     $$= center($.r, ww)      /*center this particular Pascals' row. */
     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*/
output   when using the input of:     11
                    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
output   when using the input of:     22

(Output shown at   4/5   size.)

                                                                         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
   1     20    190   1140   4845  15504  38760  77520 125970 167960 184756 167960 125970  77520  38760  15504   4845   1140    190     20      1
1     21    210   1330   5985  20349  54264 116280 203490 293930 352716 352716 293930 203490 116280  54264  20349   5985   1330    210     21      1

Ring

row = 5
for i = 0 to row - 1
    col = 1
    see left("     ",row-i)
    for k = 0 to i
        see "" + col + " "
        col = col*(i-k)/(k+1)
    next
    see nl
next

Output:

     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1

RPL

« 0 SWAP FOR n 
    "" 0 n FOR p 
       n p COMB + " " +
    NEXT 
    n 1 + DISP
  NEXT 
  7 FREEZE
» 'PASCAL' STO
8 PASCAL
Output:
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 …

RPL screens are limited to 22 characters.

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(&:sum)
  end
end
 
pascal(8){|row| puts row.join(" ").center(20)}
Output:
         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 

Or for more or less a translation of the two line Haskell version (with inject being abused a bit I know):

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)}
Output:
[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]

Run BASIC

input "number of rows? ";r
for i = 0 to r - 1
  c = 1
  print left$("                          ",(r*2)-(i*2));
  for k = 0 to i
    print using("####",c);
    c = c*(i-k)/(k+1)
  next
  print
next

Output:

Number of rows? ?5
             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1

Rust

Translation of: C
fn pascal_triangle(n: u64)
{

  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!();
  }
}

Scala

Functional solutions

Summing: Recursive row definition

  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
    }

Function to pretty print n rows:

def prettyTri(n:Int) = (1 to n) foreach {i => print(" "*(n-i)); tri(i) map (c => print(c + " ")); println}

prettyTri(5)
Output:
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Summing: Scala Stream (Recursive & Memoization)

object Blaise extends App {
  def pascalTriangle(): Stream[Vector[Int]] =
    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"))
}
Output:

See it in running in your browser by ScalaFiddle (JavaScript) or by Scastie (JVM).

Scheme

Works with: Scheme version RRS
(define (next-row row)
  (map + (cons 0 row) (append row '(0))))
 
(define (triangle row rows)
  (if (= rows 0)
      '()
      (cons row (triangle (next-row row) (- rows 1)))))

(triangle (list 1) 5)

Output:

((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))

Seed7

$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: numRows is 0;
    var array integer: values is [] (0, 1);
    var integer: row is 0;
    var integer: index is 0;
  begin
    write("Number of rows: ");
    readln(numRows);
    writeln("1" lpad succ(numRows) * 3);
    for row range 2 to numRows do
      write("" lpad (numRows - row) * 3);
      values &:= [] 0;
      for index range succ(row) downto 2 do
        values[index] +:= values[pred(index)];
        write(" " <& values[index] lpad 5);
      end for;
      writeln;
    end for;
  end func;

Sidef

func pascal(rows) {
    var row = [1]
    { | n|
        say row.join(' ')
        row = [1, {|i| row[i] + row[i+1] }.map(0 .. n-2)..., 1]
    } << 1..rows
}
 
pascal(10)

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

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)
}

Now print the Pascal triangle.

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

Swift

func pascal(n:Int)->[Int]{
    if n==1{
        let a=[1]
        print(a)
        return a
    }
    else{
        var a=pascal(n:n-1)
        var temp=a
        for i in 0..<a.count{
            if i+1==a.count{
                temp.append(1)
                break
            }
            temp[i+1] = a[i]+a[i+1]
        }
        a=temp
        print(a)
        return a
    }
}
let waste = pascal(n:10)

Tcl

Summing from Previous Rows

proc pascal_iterative n {
    if {$n < 1} {error "undefined behaviour for n < 1"}
    set row [list 1]
    lappend rows $row    
    set i 1
    while {[incr i] <= $n} {
        set prev $row
        set row [list 1]
        for {set j 1} {$j < [llength $prev]} {incr j} {
            lappend row [expr {[lindex $prev [expr {$j - 1}]] + [lindex $prev $j]}]
        }
        lappend row 1
        lappend rows $row
    }
    return $rows
}

puts [join [pascal_iterative 6] \n]
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Using binary coefficients

Translation of: BASIC
proc pascal_coefficients n {
    if {$n < 1} {error "undefined behaviour for n < 1"}
    for {set i 0} {$i < $n} {incr i} {
        set c 1
        set row [list $c]
        for {set j 0} {$j < $i} {incr j} {
            set c [expr {$c * ($i - $j) / ($j + 1)}]
            lappend row $c
        }
        lappend rows $row
    }
    return $rows
}

puts [join [pascal_coefficients 6] \n]

Combinations

Translation of: 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.

package require Tcl 8.5

proc pascal_combinations n {
    if {$n < 1} {error "undefined behaviour for n < 1"}
    for {set i 0} {$i < $n} {incr i} {
        set row [list]
        for {set j 0} {$j <= $i} {incr j} {
            lappend row [C $i $j]
        }
        lappend rows $row
    }
    return $rows
}

proc C {n k} {
    expr {[ifact $n] / ([ifact $k] * [ifact [expr {$n - $k}]])}
}

set fact_cache {1 1}
proc ifact n {
    global fact_cache
    if {$n < [llength $fact_cache]} {
        return [lindex $fact_cache $n]
    }
    set i [expr {[llength $fact_cache] - 1}]
    set sum [lindex $fact_cache $i]
    while {$i < $n} {
        incr i
        set sum [expr {$sum * $i}]
        lappend fact_cache $sum
    }
    return $sum
}

puts [join [pascal_combinations 6] \n]

Comparing Performance

set n 100
puts "calculate $n rows:"
foreach proc {pascal_iterative pascal_coefficients pascal_combinations} {
    puts "$proc: [time [list $proc $n] 100]"
}
Output:
calculate 100 rows:
pascal_iterative: 2800.14 microseconds per iteration
pascal_coefficients: 8760.98 microseconds per iteration
pascal_combinations: 38176.66 microseconds per iteration

TI-83 BASIC

Using Addition of Previous Rows

PROGRAM:PASCALTR
:Lbl IN
:ClrHome
:Disp "NUMBER OF ROWS"
:Input N
:If N < 1:Goto IN
:{N,N}→dim([A])
:"CHEATING TO MAKE IT FASTER"
:For(I,1,N)
:1→[A](1,1)
:End
:For(I,2,N)
:For(J,2,I)
:[A](I-1,J-1)+[A](I-1,J)→[A](I,J)
:End
:End
:[A]

Using nCr Function

PROGRAM:PASCALTR
:Lbl IN
:ClrHome
:Disp "NUMBER OF ROWS"
:Input N
:If N < 1:Goto IN
:{N,N}→dim([A])
:For(I,2,N)
:For(J,2,I)
:(I-1) nCr (J-1)→[A](I,J)
:End
:End
:[A]

Turing

proc pascal (n : int)
    for i : 0 .. n
        var c := 1
        for k : 0 .. i
            put c : 4 ..
            c := c * (i - k) div (k + 1)
        end for
        put ""
    end for
end pascal

pascal(5)

Output:

  1
  1   1
  1   2   1
  1   3   3   1
  1   4   6   4   1
  1   5  10  10   5   1

TypeScript

Translation of: XPL0
// 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);
Output:
                         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  

uBasic/4tH

Input "Number Of Rows: "; N
@(1) = 1
Print Tab((N+1)*3);"1"

For R = 2 To N
    Print Tab((N-R)*3+1);
    For I = R To 1 Step -1
        @(I) = @(I) + @(I-1)
        Print Using "______";@(i);
    Next
Next

Print
End

Output:

Number Of Rows: 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

0 OK, 0:380

UNIX Shell

Works with: Bourne Again SHell

Any n <= 1 will print the "1" row.

#! /bin/bash
pascal() {
    local -i n=${1:-1}
    if (( n <= 1 )); then
        echo 1
    else
        local output=$( $FUNCNAME $((n - 1)) )
        set -- $( tail -n 1 <<<"$output" )   # previous row
        echo "$output"
        printf "1 "
        while [[ -n $1 ]]; do
            printf "%d " $(( $1 + ${2:-0} ))
            shift
        done
        echo
    fi
}
pascal "$1"

Ursala

Zero maps to the empty list. Negatives are inexpressible. This solution uses a library function for binomial coefficients.

#import std
#import nat

pascal = choose**ziDS+ iota*t+ iota+ successor

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.

#import std
#import nat

pascal "n" = (next"n" sum*NiCixp) <1>

test program:

#cast %nLL

example = pascal 10
Output:
<
   <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>>

VBA

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
Output:
                          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

VBScript

Derived from the BASIC version.

Pascal_Triangle(WScript.Arguments(0))
Function Pascal_Triangle(n)
	Dim values(100)
	values(1) = 1
	WScript.StdOut.Write values(1)
	WScript.StdOut.WriteLine
	For row = 2 To n
		For i = row To 1 Step -1
			values(i) = values(i) + values(i-1)
			WScript.StdOut.Write values(i) & " "
		Next
		WScript.StdOut.WriteLine
	Next
End Function
Output:

Invoke from a command line.

F:\VBScript>cscript /nologo rosettacode-pascals_triangle.vbs 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Vedit macro language

Summing from Previous Rows

Translation of: BASIC

Vedit macro language does not have actual arrays (edit buffers are normally used for storing larger amounts of data). However, a numeric register can be used as index to access another numeric register. For example, if #99 contains value 2, then #@99 accesses contents of numeric register #2.

#100 = Get_Num("Number of rows: ", STATLINE)
#0=0; #1=1
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1)
for (#99 = 2; #99 <= #100; #99++) {
    Ins_Char(' ', COUNT, (#100-#99)*3)
    #@99 = 0
    for (#98 = #99; #98 > 0; #98--) {
	#97 = #98-1
	#@98 += #@97
	Num_Ins(#@98, COUNT, 6)
    }
    Ins_Newline
}

Using binary coefficients

Translation of: BASIC
#1 = Get_Num("Number of rows: ", STATLINE)
for (#2 = 0; #2 < #1; #2++) {
    #3 = 1
    Ins_Char(' ', COUNT, (#1-#2-1)*3)
    for (#4 = 0; #4 <= #2; #4++) {
	Num_Ins(#3, COUNT, 6)
	#3 = #3 * (#2-#4) / (#4+1)
    }
    Ins_Newline
}

Visual Basic

Works with: Visual Basic version VB6 Standard
Sub pascaltriangle()
    'Pascal's triangle
    Const m = 11
    Dim t(40) As Integer, u(40) As Integer
    Dim i As Integer, n As Integer, s As String, ss As String
    ss = ""
    For n = 1 To m
        u(1) = 1
        s = ""
        For i = 1 To n
            u(i + 1) = t(i) + t(i + 1)
            s = s & u(i) & " "
            t(i) = u(i)
        Next i
        ss = ss & s & vbCrLf
    Next n
    MsgBox ss, , "Pascal's triangle"
End Sub 'pascaltriangle
Output:
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

Visual Basic .NET

Translation of: C#
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
Output:
                                                           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

Wren

Library: Wren-fmt
Library: Wren-math
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)
Output:
                                      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   

X86 Assembly

Works with: NASM
Works with: Windows

uses: io.inc - Macro library from SASM

%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
Output:
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 

XBasic

Translation of: GW-BASIC
Works with: Windows 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
Output:
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

XPL0

include c:\cxpl\codes;

proc Pascal(N);         \Display the first N rows of Pascal's triangle
int  N;                 \if N<=0 then nothing is displayed
int  Row, I, Old(40), New(40);
[for Row:= 0 to N-1 do
        [New(0):= 1;
        for I:= 1 to Row do New(I):= Old(I-1) + Old(I);
        for I:= 1 to (N-Row-1)*2 do ChOut(0, ^ );
        for I:= 0 to Row do
                [if New(I)<100 then ChOut(0, ^ );
                IntOut(0, New(I));
                if New(I)<10 then ChOut(0, ^ );
                ChOut(0, ^ );
                ];
        New(Row+1):= 0;
        I:= Old;  Old:= New;  New:= I;
        CrLf(0);
        ];
];

Pascal(13)
Output:
                         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  

zkl

Translation of: C
fcn pascalTriangle(n){ // n<=0-->""
   foreach i in (n){
      c := 1;
      print(" "*(2*(n-1-i)));
      foreach k in (i+1){
         print("%3d ".fmt(c));
         c = c * (i-k)/(k+1);
      }
      println();
   }
}
 
pascalTriangle(8);
Output:
                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 

ZX Spectrum Basic

In edit mode insert:

 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

Then in command mode (basically don't put a number in front):

RUN
Output:
        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