Pascal's triangle: Difference between revisions

m
→‎{{header|Wren}}: Minor tidy and now uses binomial method in Math module.
m (→‎{{header|Wren}}: Minor tidy and now uses binomial method in Math module.)
 
(29 intermediate revisions by 12 users not shown)
Line 42:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F pascal(n)
V row = [1]
V k = [0]
Line 49:
row = zip(row [+] k, k [+] row).map((l, r) -> l + r)
 
pascal(7)</langsyntaxhighlight>
 
{{out}}
Line 64:
=={{header|360 Assembly}}==
{{trans|PL/I}}
<langsyntaxhighlight lang="360asm">* Pascal's triangle 25/10/2015
PASCAL CSECT
USING PASCAL,R15 set base register
Line 101:
XD DS CL12 temp
YREGS
END PASCAL</langsyntaxhighlight>
{{out}}
<pre>
Line 119:
=={{header|8th}}==
One way, using array operations:
<langsyntaxhighlight lang="forth">
\ print the array
: .arr \ a -- a
Line 135:
\ print the first 16 rows:
[1] ' pasc 16 times
</syntaxhighlight>
</lang>
 
Another way, using the relation between element 'n' and element 'n-1' in a row:
<langsyntaxhighlight lang="forth">
: ratio \ m n -- num denom
tuck n:- n:1+ swap ;
Line 160:
 
15 pasc
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
BYTE count=[10],row,item
CHAR ARRAY s(5)
Line 180:
PutE()
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pascal's_triangle.png Screenshot from Atari 8-bit computer]
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]]
 
<langsyntaxhighlight lang="ada">package Pascal is
type Row is array (Natural range <>) of Natural;
Line 210:
function Next_Row(R: Row) return Row;
end Pascal;</langsyntaxhighlight>
 
The implementation of that auxiliary package "Pascal":
 
<langsyntaxhighlight Adalang="ada">package body Pascal is
function First_Row(Max_Length: Positive) return Row is
Line 239:
end Length;
end Pascal;</langsyntaxhighlight>
 
The main program, using "Pascal". It prints the desired number of rows. The number is read from the command line.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line, Pascal; use Pascal;
 
procedure Triangle is
Line 260:
Row := Next_Row(Row);
end loop;
end Triangle;</langsyntaxhighlight>
 
{{out}}
Line 279:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">PRIO MINLWB = 8, MAXUPB = 8;
OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b),
MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b);
Line 297:
# WHILE # i < stop DO
row := row[AT 1] + row[AT 2]
OD</langsyntaxhighlight>
{{Out}}
<pre>
Line 312:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% prints the first n lines of Pascal's triangle lines %
% if n is <= 0, no output is produced %
Line 330:
printPascalTriangle( 8 )
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 341:
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="Amazing Hopper">
#include <jambo.h>
#define Mulbyandmoveto(_X_) Mul by '_X_', Move to '_X_'
 
Main
filas=0, Get arg numeric '2', Move to 'filas'
i=0, r=""
Loop if( var 'i' Is less than 'filas' )
c=1, j=0
Set 'c' To str, Move to 'r'
Loop if ( var 'j' Is less than 'i' )
Set 'i' Minus 'j', Plus one 'j', Div it; Mul by and move to 'c'
Multi cat ' r, "\t", Str(c) '; Move to 'r'
++j
Back
Printnl 'r'
++i
Back
End
</syntaxhighlight>
{{out}}
<pre>
$ hopper jm/pascal.jambo 14
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
 
</pre>
 
Line 346 ⟶ 387:
Pascal' s triangle of order ⍵
=== Dyalog APL ===
<langsyntaxhighlight lang="apl">
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}
</syntaxhighlight>
</lang>
 
example
 
<langsyntaxhighlight lang="apl">
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}5
</syntaxhighlight>
</lang>
 
<pre>
Line 367 ⟶ 408:
GNU APL doesn't allow multiple statements within lambdas so the solution is phrased differently:
 
<langsyntaxhighlight lang="apl">
{{⍉⍵∘.!⍵} 0,⍳⍵}
</syntaxhighlight>
</lang>
 
example
 
<langsyntaxhighlight lang="apl">
{{⍉⍵∘.!⍵} 0,⍳⍵} 3
</syntaxhighlight>
</lang>
 
<pre>
Line 386 ⟶ 427:
=={{header|AppleScript}}==
Drawing n rows from a generator:
<langsyntaxhighlight AppleScriptlang="applescript">-------------------- PASCAL'S TRIANGLE -------------------
 
-- pascal :: Generator [[Int]]
Line 598 ⟶ 639:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 610 ⟶ 651:
=={{header|Arturo}}==
{{trans|Nim}}
<langsyntaxhighlight lang="rebol">pascalTriangle: function [n][
triangle: new [[1]]
 
Line 622 ⟶ 663:
loop pascalTriangle 10 'row [
print pad.center join.with: " " map to [:string] row 'x -> pad.center x 5 60
]</langsyntaxhighlight>
 
{{out}}
Line 639 ⟶ 680:
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?p=276617#276617 discussion]
<langsyntaxhighlight AutoHotkeylang="autohotkey">n := 8, p0 := "1" ; 1+n rows of Pascal's triangle
Loop %n% {
p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1
Line 660 ⟶ 701:
 
GuiClose:
ExitApp</langsyntaxhighlight>
 
Alternate {{works with|AutoHotkey L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">Msgbox % format(pascalstriangle())
Return
 
Line 687 ⟶ 728:
: p[row-1, col])
Return p
}</langsyntaxhighlight>
n <= 0 returns empty
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">$ awk 'BEGIN{for(i=0;i<6;i++){c=1;r=c;for(j=0;j<i;j++){c*=(i-j)/(j+1);r=r" "c};print r}}'</langsyntaxhighlight>
{{Out}}<pre>
1
Line 700 ⟶ 741:
1 5 10 10 5 1
</pre>
 
 
=={{header|Bait}}==
<syntaxhighlight lang="bait">
// Create a Pascal's triangle with a given number of rows.
// Returns an empty array for row_nr <= 0.
fun pascals_triangle(row_nr i32) [][]i32 {
mut rows := [][]i32
 
// Iterate over all rows
for r := 0; r < row_nr; r += 1 {
// Store the row above the current one
mut above := rows[r - 1]
 
// Fill the current row. It contains r + 1 numbers
for i := 0; i <= r; i += 1 {
// First number is always 1
if i == 0 {
rows.push([1]) // Push new row
}
// Last number is always 1
else if i == r {
rows[r].push(1)
}
// Other numbers are the sum of the two numbers above them
else {
rows[r].push(above[i - 1] + above[i])
}
}
}
 
return rows
}
 
 
// Helper function to pretty print triangles.
// It still get's ugly once numbers have >= 2 digits.
fun print_triangle(triangle [][]i32) {
for i, row in triangle {
// Create string with leading spaces
mut s := ' '.repeat(triangle.length - i - 1)
 
// Add each number to the string
for n in row {
s += n.str() + ' '
}
 
// Print and trim the extra trailing space
println(s.trim_right(' '))
}
}
 
 
fun main() {
print_triangle(pascals_triangle(7))
}
</syntaxhighlight>
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
</pre>
 
 
=={{header|BASIC}}==
Line 714 ⟶ 823:
If the user enters value less than 1, the first row is still always displayed.
 
<langsyntaxhighlight lang="freebasic">DIM i AS Integer
DIM row AS Integer
DIM nrows AS Integer
Line 729 ⟶ 838:
NEXT i
PRINT
NEXT row</langsyntaxhighlight>
 
=={{header|Batch File}}==
Based from the Fortran Code.
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 771 ⟶ 880:
for /l %%A in (1,1,%numspaces%) do set "space=!space! "
goto :EOF
::/The Functions.</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 792 ⟶ 901:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> nrows% = 10
colwidth% = 4
Line 804 ⟶ 913:
NEXT
PRINT
NEXT row%</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 818 ⟶ 927:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let pascal(n) be
Line 831 ⟶ 940:
$)
let start() be pascal(8)</langsyntaxhighlight>
{{out}}
<pre> 1
Line 843 ⟶ 952:
 
=={{header|Befunge}}==
<langsyntaxhighlight Befungelang="befunge">0" :swor fo rebmuN">:#,_&> 55+, v
v01*p00-1:g00.:<1p011p00:\-1_v#:<
>g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@</langsyntaxhighlight>
{{Out}}
<pre>Number of rows: 10
Line 864 ⟶ 973:
Displays n rows.
 
<langsyntaxhighlight lang="bqn">Pascal ← {(0⊸∾+∾⟜0)⍟(↕𝕩)⋈1}
 
•Show¨Pascal 6</langsyntaxhighlight>
<syntaxhighlight lang="text">⟨ 1 ⟩
⟨ 1 1 ⟩
⟨ 1 2 1 ⟩
⟨ 1 3 3 1 ⟩
⟨ 1 4 6 4 1 ⟩
⟨ 1 5 10 10 5 1 ⟩</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( out$"Number of rows? "
& get':?R
& -1:?I
Line 892 ⟶ 1,001:
)
&
)</langsyntaxhighlight>
{{Out}}
<pre>Number of rows?
Line 906 ⟶ 1,015:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S
1
Line 925 ⟶ 1,034:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Line 931 ⟶ 1,040:
{{trans|Fortran}}
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void pascaltriangle(unsigned int n)
Line 952 ⟶ 1,061:
pascaltriangle(8);
return 0;
}</langsyntaxhighlight>
 
===Recursive===
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define D 32
Line 972 ⟶ 1,081:
int x[D] = {0, 1, 0}, y[D] = {0};
return pascals(x, y, 0);
}</langsyntaxhighlight>
 
===Adding previous row values===
 
<langsyntaxhighlight lang="c">void triangleC(int nRows) {
if (nRows <= 0) return;
int *prevRow = NULL;
Line 991 ⟶ 1,100:
}
free(prevRow);
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 997 ⟶ 1,106:
Produces no output when n is less than or equal to zero.
 
<langsyntaxhighlight lang="csharp">using System;
 
namespace RosettaCode {
Line 1,021 ⟶ 1,130:
}
}
}</langsyntaxhighlight>
 
===Arbitrarily large numbers (BigInteger), arbitrary row selection===
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Numerics;
Line 1,071 ⟶ 1,180:
}
}
}</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="csharp">static void Main()
{
IEnumerable<BigInteger[]> triangle = PascalsTriangle.GetTriangle(20);
string output = PascalsTriangle.FormatTriangleString(triangle)
Console.WriteLine(output);
}</langsyntaxhighlight>
 
{{out}}
Line 1,106 ⟶ 1,215:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <algorithm>
#include<cstdio>
Line 1,185 ⟶ 1,294:
}
 
}</langsyntaxhighlight>
===C++11 (with dynamic and semi-static vectors)===
Constructs the whole triangle in memory before printing it. Uses vector of vectors as a 2D array with variable column size. Theoretically, semi-static version should work a little faster.
<langsyntaxhighlight lang="cpp">// Compile with -std=c++11
#include<iostream>
#include<vector>
Line 1,274 ⟶ 1,383:
}
 
</syntaxhighlight>
</lang>
===C++11 (with a class) ===
A full fledged example with a class definition and methods to retrieve data, worthy of the title object-oriented.
<langsyntaxhighlight lang="cpp">// Compile with -std=c++11
#include<iostream>
#include<vector>
Line 1,358 ⟶ 1,467:
}
 
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
 
For n < 1, prints nothing, always returns nil. Copied from the Common Lisp implementation below, but with local functions and explicit tail-call-optimized recursion (recur).
<langsyntaxhighlight lang="lisp">(defn pascal [n]
(let [newrow (fn newrow [lst ret]
(if lst
Line 1,374 ⟶ 1,483:
(recur (dec n) (conj (newrow lst []) 1)))))]
(genrow n [1])))
(pascal 4)</langsyntaxhighlight>
And here's another version, using the ''partition'' function to produce the sequence of pairs in a row, which are summed and placed between two ones to produce the next row:
<langsyntaxhighlight lang="lisp">
(defn nextrow [row]
(vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] )))
Line 1,385 ⟶ 1,494:
(doseq [row triangle]
(println row))))
</syntaxhighlight>
</lang>
The ''assert'' form causes the ''pascal'' function to throw an exception unless the argument is (integral and) positive.
 
Here's a third version using the ''iterate'' function
<langsyntaxhighlight lang="lisp">
(def pascal
(iterate
Line 1,397 ⟶ 1,506:
(map (partial apply +) ,,,)))
[1]))
</syntaxhighlight>
</lang>
 
Another short version which returns an infinite pascal triangle as a list, using the iterate function.
 
<langsyntaxhighlight lang="lisp">
(def pascal
(iterate #(concat [1]
Line 1,407 ⟶ 1,516:
[1])
[1]))
</syntaxhighlight>
</lang>
 
One can then get the first n rows using the take function
 
<langsyntaxhighlight lang="lisp">
(take 10 pascal) ; returns a list of the first 10 pascal rows
</syntaxhighlight>
</lang>
 
Also, one can retrieve the nth row using the nth function
 
<langsyntaxhighlight lang="lisp">
(nth pascal 10) ;returns the nth row
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
This version assumes n is an integer and n >= 1. It efficiently computes binomial coefficients.
<langsyntaxhighlight lang="coffeescript">
pascal = (n) ->
width = 6
Line 1,453 ⟶ 1,562:
pascal(7)
 
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,468 ⟶ 1,577:
 
=={{header|Commodore BASIC}}==
<langsyntaxhighlight BASIClang="basic">10 INPUT "HOW MANY";N
20 IF N<1 THEN END
30 DIM C(N)
Line 1,491 ⟶ 1,600:
220 C(I)=D(I)
230 NEXT I
240 NEXT J</langsyntaxhighlight>
 
Output:
<syntaxhighlight lang="text">RUN
HOW MANY? 8
1
Line 1,506 ⟶ 1,615:
1 8 28 56 70 56 28 8 1
READY.
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
To evaluate, call (pascal n). For n < 1, it simply returns nil.
 
<langsyntaxhighlight lang="lisp">(defun pascal (n)
(genrow n '(1)))
 
(defun genrow (n l)
(when (< 0plusp n)
(print l)
(genrow (1- n) (cons 1 (newrow l)))))
 
(defun newrow (l)
(if (> 2null (lengthrest l))
'(1)
(cons (+ (carfirst l) (cadrsecond l)) (newrow (cdr l)))))</lang>
(newrow (rest l)))))</syntaxhighlight>
 
An iterative solution with ''loop'', using ''nconc'' instead of ''collect'' to keep track of the last ''cons''. Otherwise, it would be necessary to traverse the list to do a ''(rplacd (last a) (list 1))''.
 
<langsyntaxhighlight lang="lisp">(defun pascal-next-row (a)
(loop :for q :in a
:and p = 0 :then q
:as s = (list (+ p q))
:nconc s :into a
:finally (rplacd s (list 1))
(return a)))
 
(defun pascal (n)
(loop :for a = (list 1) :then (pascal-next-row a)
:repeat n
:collect a))</langsyntaxhighlight>
 
Another iterative solution, this time using pretty-printing to automatically print the triangle in the shape of a triangle in the terminal. The print-pascal-printtriangle function determinescomputes and uses the length of the finalprinted rowlast and uses itrow to decide how wide the triangle should be.
 
<langsyntaxhighlight lang="lisp">
(defun next-pascal-triangle-row (llist)
`(1
`(1 ,@(loop for i from 0 to (- (length l) 2)
,.(mapcar collect (#'+ (nth i l)list (nth (1+ i)rest l)list))
1))
 
(defun pascal-printtriangle (rnumber-of-rows)
(loop repeat number-of-rows
(let* ((pasc (loop with p = (list (list 1))
repeat rfor dorow = '(nconc1) pthen (list (apply #'next-pascal-triangle-row (last p)))row)
finally (returncollect p)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:
 
<langsyntaxhighlight lang="lisp">(print-pascal-printtriangle 4)</langsyntaxhighlight>
<syntaxhighlight lang="text">
1
1 1
1 2 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 2 1 1
1 3 3 1 2 1
1 4 6 1 3 34 1
1 5 10 10 1 4 6 45 1
1 6 15 120 515 10 10 56 1
1 7 21 135 635 1521 20 15 67 1
</syntaxhighlight>
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
</lang>
 
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
<langsyntaxhighlight lang="oberon2">
MODULE PascalTriangle;
IMPORT StdLog, DevCommanders, TextMappers;
Line 1,652 ⟶ 1,765:
 
END PascalTriangle.
</syntaxhighlight>
</lang>
<pre>Execute: ^Q PascalTriangle.Do 0 1 2 3 4 5 6 7 8 9 10 11 12~</pre>
{{out}}
Line 1,673 ⟶ 1,786:
=={{header|D}}==
===Less functional Version===
<langsyntaxhighlight lang="d">int[][] pascalsTriangle(in int rows) pure nothrow {
auto tri = new int[][rows];
foreach (r; 0 .. rows) {
Line 1,697 ⟶ 1,810:
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]);
}</langsyntaxhighlight>
===More functional Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
auto pascal() pure nothrow {
Line 1,709 ⟶ 1,822:
void main() {
pascal.take(5).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]</pre>
Line 1,717 ⟶ 1,830:
Their difference are the initial line and the operation that act on the line element to produce next line.
The following is a generic pascal's triangle implementation for positive number of lines output (n).
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.array, std.format;
 
string Pascal(alias dg, T, T initValue)(int n) {
Line 1,758 ⟶ 1,871:
foreach (i; [16])
writef(sierpinski(i));
}</langsyntaxhighlight>
{{out}}
<pre> 1
Line 1,793 ⟶ 1,906:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">
import 'dart:io';
 
Line 1,836 ⟶ 1,949:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">program PascalsTriangle;
 
procedure Pascal(r:Integer);
Line 1,859 ⟶ 1,972:
begin
Pascal(9);
end.</langsyntaxhighlight>
 
=={{header|DWScript}}==
Doesn't print anything for negative or null values.
<langsyntaxhighlight lang="delphi">procedure Pascal(r : Integer);
var
i, c, k : Integer;
Line 1,877 ⟶ 1,990:
end;
 
Pascal(9);</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 1,893 ⟶ 2,006:
So as not to bother with text layout, this implementation generates a HTML fragment. It uses a single mutable array, appending one 1 and adding to each value the preceding value.
 
<langsyntaxhighlight lang="e">def pascalsTriangle(n, out) {
def row := [].diverge(int)
out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>")
Line 1,912 ⟶ 2,025:
}
out.print("</table>")
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">def out := <file:triangle.html>.textWriter()
try {
pascalsTriangle(15, out)
Line 1,920 ⟶ 2,033:
out.close()
}
makeCommand("yourFavoriteWebBrowser")("triangle.html")</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
numfmt 0 4
proc pascal n . .
r[] = [ 1 ]
for i to n
rn[] = [ ]
l = 0
for j to n - len r[]
write " "
.
for r in r[]
write r
rn[] &= l + r
l = r
.
print ""
rn[] &= l
swap r[] rn[]
.
.
pascal 13
</syntaxhighlight>
 
=={{header|Eiffel}}==
 
<langsyntaxhighlight lang="eiffel">
note
description : "Prints pascal's triangle"
Line 2,026 ⟶ 2,163:
--Contains all already calculated lines
end
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Pascal do
def triangle(n), do: triangle(n,[1])
Line 2,040 ⟶ 2,177:
end
 
Pascal.triangle(8)</langsyntaxhighlight>
 
{{out}}
Line 2,056 ⟶ 2,193:
=={{header|Emacs Lisp}}==
===Using mapcar and append, returing a list of rows===
<langsyntaxhighlight lang="lisp">(require 'cl-lib)
 
(defun next-row (row)
Line 2,065 ⟶ 2,202:
(if (= rows 0)
'()
(cons row (triangle (next-row row) (- rows 1)))))</langsyntaxhighlight>
 
{{Out}}
Line 2,079 ⟶ 2,216:
</pre>
===Translation from Pascal===
<langsyntaxhighlight lang="lisp">(defun pascal (r)
(dotimes (i r)
(let ((c 1))
Line 2,086 ⟶ 2,223:
(setq c (/ (* c (- i k))
(+ k 1))))
(terpri))))</langsyntaxhighlight>
{{Out}}
From the REPL:
Line 2,100 ⟶ 2,237:
===Returning a string===
Same as the translation from Pascal, but now returning a string.
<langsyntaxhighlight lang="lisp">(defun pascal (r)
(let ((out ""))
(dotimes (i r)
Line 2,109 ⟶ 2,246:
(+ k 1))))
(setq out (concat out "\n"))))
out))</langsyntaxhighlight>
{{Out}}
Now, since this one returns a string, it is possible to insert the result in the current buffer:
Line 2,125 ⟶ 2,262:
=={{header|Erlang}}==
 
<langsyntaxhighlight lang="erlang">
-import(lists).
-export([pascal/1]).
Line 2,134 ⟶ 2,271:
[H|_] = L,
[lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,144 ⟶ 2,281:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM PASCAL_TRIANGLE
 
Line 2,162 ⟶ 2,299:
PASCAL(9)
END PROGRAM
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,178 ⟶ 2,315:
=={{header|Euphoria}}==
===Summing from Previous Rows===
<langsyntaxhighlight Euphorialang="euphoria">sequence row
row = {}
for m = 1 to 10 do
Line 2,187 ⟶ 2,324:
print(1,row)
puts(1,'\n')
end for</langsyntaxhighlight>
 
{{Out}}
Line 2,211 ⟶ 2,348:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">PASCAL
=LAMBDA(n,
BINCOEFF(n - 1)(
Line 2,224 ⟶ 2,361:
QUOTIENT(FACT(n), FACT(k) * FACT(n - k))
)
)</langsyntaxhighlight>
 
{{Out}}
Line 2,382 ⟶ 2,519:
Or defining the whole triangle as a single grid, by binding the name TRIANGLE to an additional lambda:
 
<langsyntaxhighlight lang="lisp">TRIANGLE
=LAMBDA(n,
LET(
Line 2,393 ⟶ 2,530:
)
)
)</langsyntaxhighlight>
 
{{Out}}
Line 2,550 ⟶ 2,687:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let rec nextrow l =
match l with
| [] -> []
Line 2,562 ⟶ 2,699:
printf "%s" (i.ToString() + ", ")
printfn "%s" "\n"
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Line 2,568 ⟶ 2,705:
This implementation works by summing the previous line content. Result for n < 1 is the same as for n == 1.
 
<langsyntaxhighlight lang="factor">USING: grouping kernel math sequences ;
 
: (pascal) ( seq -- newseq )
Line 2,574 ⟶ 2,711:
 
: pascal ( n -- seq )
1 - { { 1 } } swap [ (pascal) ] times ;</langsyntaxhighlight>
 
It works as:
 
<langsyntaxhighlight lang="factor">5 pascal .
{ { 1 } { 1 1 } { 1 2 1 } { 1 3 3 1 } { 1 4 6 4 1 } }</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 2,613 ⟶ 2,750:
}
}
</syntaxhighlight>
</lang>
 
=={{header|FOCAL}}==
<langsyntaxhighlight FOCALlang="focal">1.1 S OLD(1)=1; T %4.0, 1, !
1.2 F N=1,10; D 2
1.3 Q
Line 2,626 ⟶ 2,763:
 
3.1 S OLD(X)=NEW(X)
3.2 T %4.0, OLD(X)</langsyntaxhighlight>
{{output}}
<pre>
Line 2,643 ⟶ 2,780:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: init ( n -- )
here swap cells erase 1 here ! ;
: .line ( n -- )
Line 2,653 ⟶ 2,790:
: pascal ( n -- )
dup init 1 .line
1 ?do i next i 1+ .line loop ;</langsyntaxhighlight>
This is a bit more efficient.
{{trans|C}}
<langsyntaxhighlight lang="forth">: PascTriangle
cr dup 0
?do
Line 2,663 ⟶ 2,800:
;
 
13 PascTriangle</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
Prints nothing for n<=0. Output formatting breaks down for n>20
<langsyntaxhighlight lang="fortran">PROGRAM Pascals_Triangle
 
CALL Print_Triangle(8)
Line 2,693 ⟶ 2,830:
END DO
 
END SUBROUTINE Print_Triangle</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub pascalTriangle(n As UInteger)
Line 2,732 ⟶ 2,869:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,754 ⟶ 2,891:
=={{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.
<langsyntaxhighlight lang="frink">
pascal[rows] :=
{
Line 2,770 ⟶ 2,907:
 
pascal[10]
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,789 ⟶ 2,926:
=== Summing from Previous Rows ===
{{trans|Scala}}
<langsyntaxhighlight lang="funl">import lists.zip
 
def
pascal( 1 ) = [1]
pascal( n ) = [1] + map( (a, b) -> a + b, zip(pascal(n-1), pascal(n-1).tail()) ) + [1]</langsyntaxhighlight>
 
=== Combinations ===
{{trans|Haskell}}
<langsyntaxhighlight lang="funl">import integers.choose
 
def pascal( n ) = [choose( n - 1, k ) | k <- 0..n-1]</langsyntaxhighlight>
 
=== Pascal's Triangle ===
<langsyntaxhighlight lang="funl">def triangle( height ) =
width = max( map(a -> a.toString().length(), pascal(height)) )
 
Line 2,812 ⟶ 2,949:
println( map(a -> format('%' + width + 'd ', a), pascal(n)).mkString() )
 
triangle( 10 )</langsyntaxhighlight>
 
{{out}}
Line 2,830 ⟶ 2,967:
=={{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}}==
<langsyntaxhighlight lang="gap">Pascal := function(n)
local i, v;
v := [1];
Line 2,855 ⟶ 2,998:
# [ 1, 6, 15, 20, 15, 6, 1 ]
# [ 1, 7, 21, 35, 35, 21, 7, 1 ]
# [ 1, 8, 28, 56, 70, 56, 28, 8, 1 ]</langsyntaxhighlight>
 
=={{header|Go}}==
No output for n < 1. Otherwise, output formatted left justified.
<syntaxhighlight lang="go">
<lang go>
package main
 
Line 2,902 ⟶ 3,045:
printTriangle(4)
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,914 ⟶ 3,057:
=== Recursive ===
In the spirit of the Haskell "think in whole lists" solution here is a list-driven, minimalist solution:
<langsyntaxhighlight lang="groovy">def pascal
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }</langsyntaxhighlight>
However, this solution is horribly inefficient (O(''n''**2)). It slowly grinds to a halt on a reasonably powerful PC after about line 25 of the triangle.
 
Test program:
<langsyntaxhighlight lang="groovy">def count = 15
(1..count).each { n ->
printf ("%2d:", n); (0..(count-n)).each { print " " }; pascal(n).each{ printf("%6d ", it) }; println ""
}</langsyntaxhighlight>
 
{{out}}
Line 2,942 ⟶ 3,085:
 
=={{header|GW-BASIC}}==
<langsyntaxhighlight lang="qbasic">10 INPUT "Number of rows? ",R
20 FOR I=0 TO R-1
30 C=1
Line 2,950 ⟶ 3,093:
70 NEXT
80 PRINT
90 NEXT</langsyntaxhighlight>
 
Output:
Line 2,972 ⟶ 3,115:
similar function
 
<langsyntaxhighlight lang="haskell">zapWith :: (a -> a -> a) -> [a] -> [a] -> [a]
zapWith f xs [] = xs
zapWith f [] ys = ys
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys</langsyntaxhighlight>
 
Now we can shift a list and add it to itself, extending it by keeping
the ends:
 
<langsyntaxhighlight lang="haskell">extendWith f [] = []
extendWith f xs@(x:ys) = x : zapWith f xs ys</langsyntaxhighlight>
 
And for the whole (infinite) triangle, we just iterate this operation,
starting with the first row:
 
<langsyntaxhighlight lang="haskell">pascal = iterate (extendWith (+)) [1]</langsyntaxhighlight>
 
For the first ''n'' rows, we just take the first ''n'' elements from this
list, as in
 
<langsyntaxhighlight lang="haskell">*Main> take 6 pascal
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]</langsyntaxhighlight>
 
A shorter approach, plagiarized from [http://www.haskell.org/haskellwiki/Blow_your_mind]
<langsyntaxhighlight lang="haskell">-- generate next row from current row
nextRow row = zipWith (+) ([0] ++ row) (row ++ [0])
 
-- returns the first n rows
pascal = iterate nextRow [1]</langsyntaxhighlight>
 
Alternatively, using list comprehensions:
 
<langsyntaxhighlight lang="haskell">
pascal :: [[Integer]]
pascal =
(1 : [ 0 | _ <- head pascal])
: [zipWith (+) (0:row) row | row <- pascal]
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="haskell">
*Pascal> take 5 <$> (take 5 $ triangle)
[[1,0,0,0,0],[1,1,0,0,0],[1,2,1,0,0],[1,3,3,1,0],[1,4,6,4,1]]
</syntaxhighlight>
</lang>
 
With binomial coefficients:
<langsyntaxhighlight lang="haskell">fac = product . enumFromTo 1
 
binCoef n k = fac n `div` (fac k * fac (n - k))
 
pascal = ((fmap . binCoef) <*> enumFromTo 0) . pred</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="haskell">*Main> putStr $ unlines $ map unwords $ map (map show) $ pascal 10
1
1 1
Line 3,034 ⟶ 3,177:
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
</syntaxhighlight>
</lang>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest"> CALL Pascal(30)
 
SUBROUTINE Pascal(rows)
Line 3,051 ⟶ 3,194:
ENDDO
ENDDO
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The code below is slightly modified from the library version of pascal which prints 0's to the full width of the carpet.
It also presents the data as an isoceles triangle.
<langsyntaxhighlight Iconlang="icon">link math
procedure main(A)
Line 3,075 ⟶ 3,218:
write()
}
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 3,101 ⟶ 3,244:
 
=={{header|IDL}}==
<langsyntaxhighlight IDLlang="idl">Pro Pascal, n
;n is the number of lines of the triangle to be displayed
r=[1]
Line 3,117 ⟶ 3,260:
print, r
 
End</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "PascalTr.bas"
110 TEXT 80
120 LET ROW=12
Line 3,131 ⟶ 3,274:
190 NEXT
200 PRINT
210 NEXT</langsyntaxhighlight>
 
{{out}}
Line 3,149 ⟶ 3,292:
 
=={{header|ivy}}==
<langsyntaxhighlight lang="ivy">
op pascal N = transp (0 , iota N) o.! -1 , iota N
pascal 5
Line 3,158 ⟶ 3,301:
1 4 6 4 1 0
1 5 10 10 5 1
</syntaxhighlight>
</lang>
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> !~/~ i.5
1 0 0 0 0
1 1 0 0 0
1 2 1 0 0
1 3 3 1 0
1 4 6 4 1</langsyntaxhighlight>
 
<langsyntaxhighlight lang="j"> ([: ":@-.&0"1 !~/~)@i. 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1</langsyntaxhighlight>
 
<langsyntaxhighlight lang="j"> (-@|. |."_1 [: ":@-.&0"1 !~/~)@i. 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1</langsyntaxhighlight>
 
However, multi-digit numbers take up additional space, which looks slightly odd. But we can work around that by adding additional padding and shifting the lines a bit more:
 
<syntaxhighlight lang=J> (|."_1~ 0-3*i.@-@#) ;@((<'%6d') sprintf each -.&0)"1 !~/~i.10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
</syntaxhighlight>
 
Also... when we mix positive and negative numbers it stops being a triangle:
 
<syntaxhighlight lang=J> i:5
_5 _4 _3 _2 _1 0 1 2 3 4 5
!~/~i:5
1 0 0 0 0 1 _5 15 _35 70 _126
_4 1 0 0 0 1 _4 10 _20 35 _56
6 _3 1 0 0 1 _3 6 _10 15 _21
_4 3 _2 1 0 1 _2 3 _4 5 _6
1 _1 1 _1 1 1 _1 1 _1 1 _1
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 1 2 1 0 0 0
0 0 0 0 0 1 3 3 1 0 0
0 0 0 0 0 1 4 6 4 1 0
0 0 0 0 0 1 5 10 10 5 1
!/~i:5
1 _4 6 _4 1 0 0 0 0 0 0
0 1 _3 3 _1 0 0 0 0 0 0
0 0 1 _2 1 0 0 0 0 0 0
0 0 0 1 _1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1
_5 _4 _3 _2 _1 0 1 2 3 4 5
15 10 6 3 1 0 0 1 3 6 10
_35 _20 _10 _4 _1 0 0 0 1 4 10
70 35 15 5 1 0 0 0 0 1 5
_126 _56 _21 _6 _1 0 0 0 0 0 1</syntaxhighlight>
 
 
 
See the [[Talk:Pascal's_triangle#J_Explanation|talk page]] for explanation of earlier version
Line 3,189 ⟶ 3,378:
===Summing from Previous Rows===
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java">import java.util.ArrayList;
...//class definition, etc.
public static void genPyrN(int rows){
Line 3,209 ⟶ 3,398:
System.out.println(thisRow);
}
}</langsyntaxhighlight>
 
===Combinations===
This method is limited to 21 rows because of the limits of <tt>long</tt>. Calling <tt>pas</tt> with an argument of 22 or above will cause intermediate math to wrap around and give false answers.
<langsyntaxhighlight lang="java">public class Pas{
public static void main(String[] args){
//usage
Line 3,239 ⟶ 3,428:
return ans;
}
}</langsyntaxhighlight>
 
===Using arithmetic calculation of each row element ===
This method is limited to 30 rows because of the limits of integer calculations (probably when calculating the multiplication). If m is declared as long then 62 rows can be printed.
<langsyntaxhighlight lang="java">
public class Pascal {
private static void printPascalLine (int n) {
Line 3,263 ⟶ 3,452:
}
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
Line 3,270 ⟶ 3,459:
{{works with|SpiderMonkey}}
{{works with|V8}}
<langsyntaxhighlight lang="javascript">// Pascal's triangle object
function pascalTriangle (rows) {
 
Line 3,340 ⟶ 3,529:
// Display 8 row triangle in base 16
tri = new pascalTriangle(8);
tri.print(16);</langsyntaxhighlight>
Output:
<pre>$ d8 pascal.js
Line 3,358 ⟶ 3,547:
====Functional====
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(function (n) {
'use strict';
 
Line 3,459 ⟶ 3,648:
}), false, 'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n');
})(7);</langsyntaxhighlight>
{{Out}}
{| class="wikitable" style="text-align:center;width:26em;height:26em;table-layout:fixed;"
Line 3,478 ⟶ 3,667:
|}
 
<langsyntaxhighlight JavaScriptlang="javascript">[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1],[1,6,15,20,15,6,1]]</langsyntaxhighlight>
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 3,589 ⟶ 3,778:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 3,603 ⟶ 3,792:
 
====Recursive====
<langsyntaxhighlight lang="javascript">
const aux = n => {
if(n <= 1) return [1]
Line 3,616 ⟶ 3,805:
}
pascal(8)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,629 ⟶ 3,818:
</pre>
====Recursive - memoized====
<langsyntaxhighlight lang="javascript">
const aux = (() => {
const layers = [[1], [1]]
Line 3,646 ⟶ 3,835:
}
pascal(8)
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 3,653 ⟶ 3,842:
each corresponding to a row of the Pascal triangle.
The implementation avoids any arithmetic except addition.
<langsyntaxhighlight lang="jq"># pascal(n) for n>=0; pascal(0) emits an empty stream.
def pascal(n):
def _pascal: # input: the previous row
Line 3,663 ⟶ 3,852:
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] | _pascal
end;
if n <= 0 then empty else [1] | _pascal end ;</langsyntaxhighlight>
'''Example''':
pascal(5)
{{ Out }}
<langsyntaxhighlight lang="sh">$ jq -c -n -f pascal_triangle.jq
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]</langsyntaxhighlight>
 
'''Using recurse/1'''
 
Here is an equivalent implementation that uses the built-in filter, recurse/1, instead of the inner function.
<langsyntaxhighlight lang="jq">def pascal(n):
if n <= 0 then empty
else [1]
Line 3,685 ⟶ 3,874:
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1]
end)
end;</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 3,714 ⟶ 3,903:
Another solution using matrix exponentiation.
 
<syntaxhighlight lang="julia">
<lang Julia>
iround(x) = round(Int64, x)
 
Line 3,724 ⟶ 3,913:
end
 
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,740 ⟶ 3,929:
Yet another solution using a static vector
 
<syntaxhighlight lang="julia">
<lang Julia>
function pascal(n)
(n<=0) && error("Pascal trinalge can not have zero or negative rows")
Line 3,756 ⟶ 3,945:
end
end
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,773 ⟶ 3,962:
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
pascal:{(x-1){+':x,0}\1}
pascal 6
Line 3,781 ⟶ 3,970:
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="kotlin">fun pas(rows: Int) {
for (i in 0..rows - 1) {
for (j in 0..i)
Line 3,801 ⟶ 3,990:
}
 
fun main(args: Array<String>) = pas(args[0].toInt())</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
1) Based on this expression of pascalian binomial:
 
Line 3,842 ⟶ 4,031:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">input "How much rows would you like? "; n
dim a$(n)
 
Line 3,863 ⟶ 4,052:
next i
 
end</langsyntaxhighlight>
 
=={{header|Locomotive Basic}}==
 
<langsyntaxhighlight lang="locobasic">10 CLS
20 INPUT "Number of rows? ", rows:GOSUB 40
30 END
Line 3,878 ⟶ 4,067:
100 PRINT
110 NEXT
120 RETURN</langsyntaxhighlight>
 
Output:
Line 3,894 ⟶ 4,083:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to pascal :n
if :n = 1 [output [1]]
localmake "a pascal :n-1
Line 3,900 ⟶ 4,089:
end
 
for [i 1 10] [print pascal :i]</langsyntaxhighlight>
 
=={{header|Logtalk}}==
Our implementation will have an object <code>pascals</code> with work done in the method <code>triangle/2</code>. We will be caching results for time efficiency at the cost of space efficiency,and the <code>reset/0</code> method will flush that cache should it grow to be a problem. The resulting object looks like this:
<syntaxhighlight lang="logtalk">
:- object(pascals).
 
:- uses(integer, [plus/3, succ/2]).
 
:- public(reset/0).
 
reset :-
retractall(triangle_(_,_,_)).
:- private(triangle_/3).
:- dynamic(triangle_/3).
 
:- public(triangle/2).
 
triangle(N, Lines) :-
triangle(N, _, DiffLines),
difflist::as_list(DiffLines, Lines).
 
% Shortcut with cached value if it exists.
triangle(N, Line, DiffLines) :- triangle_(N, Line, DiffLines), !.
 
triangle(N, Line, DiffLines) :-
succ(N0, N),
triangle(N0, Line0, DiffLines0),
ZL = [0|Line0],
list::append(Line0, [0], ZR),
meta::map(plus, ZL, ZR, Line),
difflist::add(Line, DiffLines0, DiffLines),
asserta(triangle_(N, Line, DiffLines)).
 
triangle(1, [1], [[1]|X]-X).
 
:- end_object.
</syntaxhighlight>
 
{{Out}}
 
Using the SWI-Prolog back-end:
 
<pre>
?- logtalk_load([meta(loader), types(loader), pascals], [optimize(on)]).
% messages elided
true.
 
?- pascals::triangle(17, Ls), logtalk::print_message(information, user, Ls).
% - [1]
% - [1,1]
% - [1,2,1]
% - [1,3,3,1]
% - [1,4,6,4,1]
% - [1,5,10,10,5,1]
% - [1,6,15,20,15,6,1]
% - [1,7,21,35,35,21,7,1]
% - [1,8,28,56,70,56,28,8,1]
% - [1,9,36,84,126,126,84,36,9,1]
% - [1,10,45,120,210,252,210,120,45,10,1]
% - [1,11,55,165,330,462,462,330,165,55,11,1]
% - [1,12,66,220,495,792,924,792,495,220,66,12,1]
% - [1,13,78,286,715,1287,1716,1716,1287,715,286,78,13,1]
% - [1,14,91,364,1001,2002,3003,3432,3003,2002,1001,364,91,14,1]
% - [1,15,105,455,1365,3003,5005,6435,6435,5005,3003,1365,455,105,15,1]
% - [1,16,120,560,1820,4368,8008,11440,12870,11440,8008,4368,1820,560,120,16,1]
Ls = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4|...], [1, 5, 10|...], [1, 6|...], [1|...], [...|...]|...].
 
?-
</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function nextrow(t)
local ret = {}
Line 3,918 ⟶ 4,177:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1);
 
f(3);</langsyntaxhighlight>
1
1 1
Line 3,929 ⟶ 4,188:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">n=7;
<lang Mathematica>n=7;
Column[StringReplace[ToString /@ Replace[MatrixExp[SparseArray[
{Band[{2,1}] -> Range[n-1]},{n,n}]],{x__,0..}->{x},2] ,{"{"|"}"|","->" "}], Center]</langsyntaxhighlight>
[[File:MmaPascal.png]]
 
A more graphical output with arrows would involve the plotting functionality with Graph[]:
<langsyntaxhighlight Mathematicalang="mathematica">nmax := 10;
pascal[nmax_] := Module[
{vals = Table[Binomial[n, k], {n, 0, nmax}, {k, 0, n}],
Line 3,954 ⟶ 4,213:
];
pascal[nmax]
</syntaxhighlight>
</lang>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
A matrix containing the pascal triangle can be obtained this way:
<syntaxhighlight lang MATLAB="matlab">pascal(n);</langsyntaxhighlight>
 
<pre>>> pascal(6)
Line 3,974 ⟶ 4,233:
 
The binomial coefficients can be extracted from the Pascal triangle in this way:
<langsyntaxhighlight MATLABlang="matlab"> binomCoeff = diag(rot90(pascal(n)))', </langsyntaxhighlight>
 
<pre>>> for k=1:6,diag(rot90(pascal(k)))', end
Line 4,024 ⟶ 4,283:
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
<lang maxima>sjoin(v, j) := apply(sconcat, rest(join(makelist(j, length(v)), v)))$
sjoin(v, j) := apply(sconcat, rest(join(makelist(j, length(v)), v)))$
 
display_pascal_triangle(n) := for i from 0 thru 6 do disp(sjoin(makelist(binomial(i, j), j, 0, i), " "));
Line 4,035 ⟶ 4,295:
"1 4 6 4 1"
"1 5 10 10 5 1"
"1 6 15 20 15 6 1" */</lang>
</syntaxhighlight>
 
=={{header|Metafont}}==
Line 4,041 ⟶ 4,302:
(The formatting starts to be less clear when numbers start to have more than two digits)
 
<langsyntaxhighlight lang="metafont">vardef bincoeff(expr n, k) =
save ?;
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor )
Line 4,058 ⟶ 4,319:
 
pascaltr(4);
end</langsyntaxhighlight>
 
=={{header|Microsoft Small Basic}}==
{{trans|GW-BASIC}}
<langsyntaxhighlight lang="microsoftsmallbasic">
TextWindow.Write("Number of rows? ")
r = TextWindow.ReadNumber()
Line 4,074 ⟶ 4,335:
TextWindow.WriteLine("")
EndFor
</syntaxhighlight>
</lang>
 
Output:
Line 4,089 ⟶ 4,350:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE Pascal;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 4,121 ⟶ 4,382:
 
ReadChar
END Pascal.</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 4,164 ⟶ 4,425:
end n_
return fac /*calc. factorial*/
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,184 ⟶ 4,445:
 
(pascal.nial)
<langsyntaxhighlight lang="nial">factorial is recur [ 0 =, 1 first, pass, product, -1 +]
combination is fork [ > [first, second], 0 first,
/ [factorial second, * [factorial - [second, first], factorial first] ]
]
pascal is transpose each combination cart [pass, pass] tell</langsyntaxhighlight>
Using it
<langsyntaxhighlight lang="nial">|loaddefs 'pascal.nial'
|pascal 5</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import sequtils, strutils
 
proc printPascalTriangle(n: int) =
Line 4,216 ⟶ 4,477:
echo line.center(lineLength)
 
printPascalTriangle(10)</langsyntaxhighlight>
 
{{out}}
Line 4,231 ⟶ 4,492:
 
A more optimized solution that doesn't require importing, but produces, naturally, uglier output, would look like this:
<langsyntaxhighlight lang="nim">const ROWS = 10
const TRILEN = toInt(ROWS * (ROWS + 1) / 2) # Sum of arth progression
var triangle = newSeqOfCap[Natural](TRILEN) # Avoid reallocations
Line 4,243 ⟶ 4,504:
if row + 1 <= ROWS: printPascalTri(row + 1, result)
 
printPascalTri(1, triangle)</langsyntaxhighlight>
 
{{out}}
Line 4,259 ⟶ 4,520:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">(* generate next row from current row *)
let next_row row =
List.map2 (+) ([0] @ row) (row @ [0])
Line 4,268 ⟶ 4,529:
if i = n then []
else row :: loop (i+1) (next_row row)
in loop 0 [1]</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">function pascaltriangle(h)
for i = 0:h-1
for k = 0:h-i
Line 4,283 ⟶ 4,544:
endfunction
 
pascaltriangle(4);</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 4,289 ⟶ 4,550:
No result if n <= 0
 
<langsyntaxhighlight Oforthlang="oforth">: pascal(n) [ 1 ] #[ dup println dup 0 + 0 rot + zipWith(#+) ] times(n) drop ;</langsyntaxhighlight>
 
{{out}}
Line 4,307 ⟶ 4,568:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {NextLine Xs}
{List.zip 0|Xs {Append Xs [0]}
Line 4,337 ⟶ 4,598:
end
in
{PrintTriangle {Triangle 5}}</langsyntaxhighlight>
 
For n = 0, prints nothing. For negative n, throws an exception.
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">pascals_triangle(N)= {
my(row=[],prevrow=[]);
for(x=1,N,
Line 4,356 ⟶ 4,617:
print(row);
);
}</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program PascalsTriangle(output);
 
procedure Pascal(r : Integer);
Line 4,379 ⟶ 4,640:
begin
Pascal(9)
end.</langsyntaxhighlight>
Output:
<pre>% ./PascalsTriangle
Line 4,395 ⟶ 4,656:
=={{header|Perl}}==
These functions perform as requested in the task: they print out the first ''n'' lines. If ''n'' <= 0, they print nothing. The output is simple (no fancy formatting).
<langsyntaxhighlight lang="perl">sub pascal {
my $rows = shift;
my @next = (1);
Line 4,402 ⟶ 4,663:
@next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1);
}
}</langsyntaxhighlight>
 
If you want more than 68 rows, then use either "use bigint" or "use Math::GMP qw/:constant/" inside the function to enable bigints. We can also use a binomial function which will expand to bigints if many rows are requested:
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/binomial/;
sub pascal {
my $rows = shift;
Line 4,412 ⟶ 4,673:
print join(" ", map { binomial($n,$_) } 0 .. $n), "\n";
}
}</langsyntaxhighlight>
 
Here is a non-obvious version using bignum, which is limited to the first 23 rows because of the algorithm used:
<langsyntaxhighlight lang="perl">use bignum;
sub pascal_line { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 }
sub pascal { print "@{[map -+-$_, pascal_line $_]}\n" for 0..$_[0]-1 }</langsyntaxhighlight>
 
This triangle is build using the 'sock' or 'hockey stick' pattern property. Here I use the word tartaglia and not pascal because in my country it's called after the Niccolò Fontana, known also as Tartaglia. A full graphical implementation of 16 properties that can be found in the triangle can be found at mine [https://github.com/LorenzoTa/Tartaglia-s-triangle Tartaglia's triangle]
 
<langsyntaxhighlight lang="perl">
#!/usr/bin/perl
use strict;
Line 4,456 ⟶ 4,717:
my @third = tartaglia_row(5);
print "@third\n";
</syntaxhighlight>
</lang>
 
which output
Line 4,473 ⟶ 4,734:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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: #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 ⟶ 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: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre style="font-size: 8px">
Line 4,507 ⟶ 4,768:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
<?php
//Author Ivan Gavryshin @dcc0
Line 4,553 ⟶ 4,814:
?>
</langsyntaxhighlight> =={{header|PHP}}==
<langsyntaxhighlight lang="php">function pascalsTriangle($num){
$c = 1;
$triangle = Array();
Line 4,576 ⟶ 4,837:
}
echo '<br>';
}</langsyntaxhighlight>
1
1 1
Line 4,586 ⟶ 4,847:
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">
%Author: Petar Kabashki
spatr([]) = [].
spatr([_|T]) = A, T = [] => A = [].
spatr([H|T]) = A, T = [TH|_] => A = [H+TH] ++ spatr(T).
 
table
patr(0) = [1].
patr(1) = [1, 1].
patr(N) = A, N > 1 => Apre = patr(N-1), A = [1] ++ spatr(Apre) ++ [1].
 
foreach(I in 0 .. 10) println(patr(I)) end.
</syntaxhighlight>
<syntaxhighlight lang="picat">
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]
[1,5,10,10,5,1]
[1,6,15,20,15,6,1]
[1,7,21,35,35,21,7,1]
[1,8,28,56,70,56,28,8,1]
[1,9,36,84,126,126,84,36,9,1]
[1,10,45,120,210,252,210,120,45,10,1]
</syntaxhighlight>
 
=={{header|PicoLisp}}==
{{trans|C}}
<langsyntaxhighlight PicoLisplang="picolisp">(de pascalTriangle (N)
(for I N
(space (* 2 (- N I)))
Line 4,596 ⟶ 4,885:
(prin (align 3 C) " ")
(setq C (*/ C (- I K) K)) ) )
(prinl) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare (t, u)(40) fixed binary;
declare (i, n) fixed binary;
Line 4,615 ⟶ 4,904:
t = u;
end;
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="text">
1
1 1
Line 4,629 ⟶ 4,918:
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
</syntaxhighlight>
</lang>
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion">printpascal = (n) :
if (n < 1) :
1 print
Line 4,649 ⟶ 4,938:
.
 
printpascal(read number integer)</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">
$Infinity = 1
$NewNumbers = $null
Line 4,717 ⟶ 5,006:
$Infinity++
}
</syntaxhighlight>
</lang>
 
Save the above code to a .ps1 script file and start it by calling its name and providing N.
Line 4,746 ⟶ 5,035:
=={{header|Prolog}}==
Difference-lists are used to make quick append.
<langsyntaxhighlight Prologlang="prolog">pascal(N) :-
pascal(1, N, [1], [[1]|X]-X, L),
maplist(my_format, L).
Line 4,782 ⟶ 5,071:
my_writef(X) :-
writef(' %5r', [X]).
</syntaxhighlight>
</lang>
 
Output :
<langsyntaxhighlight Prologlang="prolog"> ?- pascal(15).
1
1 1
Line 4,803 ⟶ 5,092:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
true.
</syntaxhighlight>
</lang>
===An alternative===
The above use of difference lists is a really innovative example of late binding. Here's an alternative source which, while possibly not as efficient (or as short) as the previous example, may be a little easier to read and understand.
<langsyntaxhighlight lang="prolog">%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Produce a pascal's triangle of depth N
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Line 4,834 ⟶ 5,123:
pascal(N, Triangle), member(Row, Triangle), % Iterate and write each row
write(Row), nl, fail.
pascal(_).</langsyntaxhighlight>
*Output*:
<langsyntaxhighlight lang="prolog">?- pascal(5).
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]</langsyntaxhighlight>
 
=={{header|PureBasic}}==
 
<langsyntaxhighlight PureBasiclang="purebasic">Procedure pascaltriangle( n.i)
For i= 0 To n
Line 4,861 ⟶ 5,150:
Parameter.i = Val(ProgramParameter(0))
pascaltriangle(Parameter);
Input()</langsyntaxhighlight>
 
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">def pascal(n):
"""Prints out n rows of Pascal's triangle.
It returns False for failure and True for success."""
Line 4,873 ⟶ 5,162:
print row
row=[l+r for l,r in zip(row+k,k+row)]
return n>=1</langsyntaxhighlight>
 
or by creating a scan function:
<langsyntaxhighlight Pythonlang="python">def scan(op, seq, it):
a = []
result = it
Line 4,892 ⟶ 5,181:
 
for row in pascal(4):
print(row)</langsyntaxhighlight>
 
===Functional===
Line 4,899 ⟶ 5,188:
 
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Pascal's triangle'''
 
from itertools import (accumulate, chain, islice)
Line 4,995 ⟶ 5,284:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 5,013 ⟶ 5,302:
 
=={{header|q}}==
<syntaxhighlight lang="q">
<lang q>
pascal:{(x-1){0+':x,0}\1}
pascal 5
Line 5,021 ⟶ 5,310:
1 3 3 1
1 4 6 4 1
</syntaxhighlight>
</lang>
 
=={{header|Qi}}==
{{trans|Haskell}}
<syntaxhighlight lang="qi">
<lang Qi>
(define iterate
_ _ 0 -> []
Line 5,035 ⟶ 5,324:
(define pascal
N -> (iterate next-row [1] N))
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
Line 5,041 ⟶ 5,330:
The behaviour of <code>pascal</code> for values less than 1 is the same as its behaviour for 1.
 
<langsyntaxhighlight Quackerylang="quackery"> [ over size -
space swap of
swap join ] is justify ( $ n --> )
Line 5,062 ⟶ 5,351:
echoline ] is pascal ( n --> )
16 pascal</langsyntaxhighlight>
 
{{out}}
Line 5,086 ⟶ 5,375:
=={{header|R}}==
{{trans|Octave}}
<langsyntaxhighlight Rlang="r">pascalTriangle <- function(h) {
for(i in 0:(h-1)) {
s <- ""
Line 5,095 ⟶ 5,384:
print(s)
}
}</langsyntaxhighlight>
 
Here's an R version:
 
<langsyntaxhighlight Rlang="r">pascalTriangle <- function(h) {
lapply(0:h, function(i) choose(i, 0:i))
}</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 5,107 ⟶ 5,396:
Iterative version by summing rows up to <math>n</math>.
 
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (pascal n)
Line 5,119 ⟶ 5,408:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 5,127 ⟶ 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:
<syntaxhighlight lang="raku" perl6line>sub pascal {
[1], { [0, |$_ Z+ |$_, 0] } ... *
}
.say for pascal[^10];</langsyntaxhighlight>
 
One problem with the routine above is that it might recalculate the sequence each time you call it. Slightly more idiomatic would be to define the sequence as a lazy constant. Here we use the <tt>@</tt> sigil to indicate that the sequence should cache its values for reuse, and use an explicit parameter <tt>$prev</tt> for variety:
 
<syntaxhighlight lang="raku" perl6line>constant @pascal = [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... *;
.say for @pascal[^10];</langsyntaxhighlight>
 
Since we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error.
Line 5,145 ⟶ 5,434:
{{trans|Haskell}}
 
<syntaxhighlight lang="raku" perl6line>multi sub pascal (1) { $[1] }
multi sub pascal (Int $n where 2..*) {
my @rows = pascal $n - 1;
Line 5,151 ⟶ 5,440:
}
.say for pascal 10;</langsyntaxhighlight>
 
Non-positive inputs throw a multiple-dispatch error.
Line 5,158 ⟶ 5,447:
 
{{trans|Perl}}
<syntaxhighlight lang="raku" perl6line>sub pascal ($n where $n >= 1) {
say my @last = 1;
for 1 .. $n - 1 -> $row {
Line 5,166 ⟶ 5,455:
}
pascal 10;</langsyntaxhighlight>
 
Non-positive inputs throw a type check error.
Line 5,195 ⟶ 5,484:
RapidQ does not require simple variables to be declared before use.
 
<langsyntaxhighlight lang="rapidq">DEFINT values(100) = {0,1}
 
INPUT "Number of rows: "; nrows
Line 5,206 ⟶ 5,495:
NEXT i
PRINT
NEXT row</langsyntaxhighlight>
 
===Using binary coefficients===
{{trans|BASIC}}
<langsyntaxhighlight lang="rapidq">INPUT "Number of rows: "; nrows
FOR row = 0 TO nrows-1
c = 1
Line 5,219 ⟶ 5,508:
NEXT i
PRINT
NEXT row</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red[]
pascal-triangle: function [
n [ integer! ] "number of rows"
Line 5,235 ⟶ 5,524:
row: left + right
]
]</langsyntaxhighlight>
Output:
<pre>
Line 5,249 ⟶ 5,538:
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">2 elements i j
: pascalTriangle
cr dup
[ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop
;
13 pascalTriangle</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 5,271 ⟶ 5,560:
:::* &nbsp; Tartaglia's triangle
:::* &nbsp; Yang Hui's triangle
<langsyntaxhighlight lang="rexx">/*REXX program displays (or writes to a file) Pascal's triangle (centered/formatted).*/
numeric digits 3000 /*be able to handle gihugeic triangles.*/
parse arg nn . /*obtain the optional argument from CL.*/
Line 5,294 ⟶ 5,583:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure; !=1; do j=2 to arg(1); != !*j; end /*j*/; return ! /*compute factorial*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 11 </tt>}}
<pre>
Line 5,338 ⟶ 5,627:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
row = 5
for i = 0 to row - 1
Line 5,349 ⟶ 5,638:
see nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,358 ⟶ 5,647:
1 4 6 4 1
</pre>
 
=={{header|RPL}}==
« 0 SWAP '''FOR''' n
"" 0 n '''FOR''' p
n p COMB + " " +
'''NEXT'''
n 1 + DISP
'''NEXT'''
7 FREEZE
» '<span style="color:blue">PASCAL</span>' STO
 
8 <span style="color:blue">PASCAL</span>
{{out}}
<pre>
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 …
</pre>
RPL screens are limited to 22 characters.
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def pascal(n)
raise ArgumentError, "must be positive." if n < 1
yield ar = [1]
Line 5,369 ⟶ 5,683:
end
pascal(8){|row| puts row.join(" ").center(20)}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,384 ⟶ 5,698:
Or for more or less a translation of the two line Haskell version (with inject being abused a bit I know):
 
<langsyntaxhighlight lang="ruby">def next_row(row) ([0] + row).zip(row + [0]).collect {|l,r| l + r } end
 
def pascal(n) n.times.inject([1]) {|x,_| next_row x } end
 
8.times{|i| p pascal(i)}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,402 ⟶ 5,716:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">input "number of rows? ";r
for i = 0 to r - 1
c = 1
Line 5,411 ⟶ 5,725:
next
print
next</langsyntaxhighlight>Output:
<pre>Number of rows? ?5
1
Line 5,421 ⟶ 5,735:
=={{header|Rust}}==
{{trans|C}}
<langsyntaxhighlight lang="rust">
fn pascal_triangle(n: u64)
{
Line 5,437 ⟶ 5,751:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
===Functional solutions===
====Summing: Recursive row definition====
<langsyntaxhighlight lang="scala">
def tri(row: Int): List[Int] =
row match {
case 1 => List(1)
case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1
}</langsyntaxhighlight>
Function to pretty print n rows:
<langsyntaxhighlight lang="scala">def prettyTri(n:Int) = (1 to n) foreach {i => print(" "*(n-i)); tri(i) map (c => print(c + " ")); println}
 
prettyTri(5)</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 5,459 ⟶ 5,773:
1 4 6 4 1</pre>
====Summing: Scala Stream (Recursive & Memoization)====
<langsyntaxhighlight Scalalang="scala">object Blaise extends App {
def pascalTriangle(): Stream[Vector[Int]] =
Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1)
Line 5,468 ⟶ 5,782:
println("Pascal's Triangle")
output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line"))
}</langsyntaxhighlight>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/8VqiX0P/1 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/c3dDWMCcT3eoydy6QJcWCw Scastie (JVM)].
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<langsyntaxhighlight lang="scheme">(define (next-row row)
(map + (cons 0 row) (append row '(0))))
Line 5,482 ⟶ 5,796:
 
(triangle (list 1) 5)
</syntaxhighlight>
</lang>
Output:
<syntaxhighlight lang="text">((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 5,508 ⟶ 5,822:
writeln;
end for;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func pascal(rows) {
var row = [1]
{ | n|
Line 5,519 ⟶ 5,833:
}
 
pascal(10)</langsyntaxhighlight>
 
=={{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).
 
<langsyntaxhighlight lang="stata">function pascal1(n) {
return(comb(J(1,n,0::n-1),J(n,1,0..n-1)))
}
Line 5,549 ⟶ 5,863:
}
return(s)
}</langsyntaxhighlight>
 
Now print the Pascal triangle.
 
<langsyntaxhighlight lang="stata">function print_pascal_triangle(n) {
a = pascal1(n)
for (i=1; i<=n; i++) {
Line 5,568 ⟶ 5,882:
1 2 1
1 3 3 1
1 4 6 4 1</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func pascal(n:Int)->[Int]{
if n==1{
let a=[1]
Line 5,593 ⟶ 5,907:
}
let waste = pascal(n:10)
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
===Summing from Previous Rows===
<langsyntaxhighlight lang="tcl">proc pascal_iterative n {
if {$n < 1} {error "undefined behaviour for n < 1"}
set row [list 1]
Line 5,614 ⟶ 5,928:
}
 
puts [join [pascal_iterative 6] \n]</langsyntaxhighlight>
<pre>1
1 1
Line 5,623 ⟶ 5,937:
===Using binary coefficients===
{{trans|BASIC}}
<langsyntaxhighlight lang="tcl">proc pascal_coefficients n {
if {$n < 1} {error "undefined behaviour for n < 1"}
for {set i 0} {$i < $n} {incr i} {
Line 5,637 ⟶ 5,951:
}
 
puts [join [pascal_coefficients 6] \n]</langsyntaxhighlight>
===Combinations===
{{trans|Java}}
Thanks to Tcl 8.5's arbitrary precision integer arithmetic, this solution is not limited to a couple of dozen rows. Uses a caching factorial calculator to improve performance.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc pascal_combinations n {
Line 5,675 ⟶ 5,989:
}
 
puts [join [pascal_combinations 6] \n]</langsyntaxhighlight>
 
===Comparing Performance===
<langsyntaxhighlight lang="tcl">set n 100
puts "calculate $n rows:"
foreach proc {pascal_iterative pascal_coefficients pascal_combinations} {
puts "$proc: [time [list $proc $n] 100]"
}</langsyntaxhighlight>
{{Out}}
<pre>calculate 100 rows:
Line 5,691 ⟶ 6,005:
=={{header|TI-83 BASIC}}==
===Using Addition of Previous Rows===
<langsyntaxhighlight lang="ti83b">PROGRAM:PASCALTR
:Lbl IN
:ClrHome
Line 5,707 ⟶ 6,021:
:End
:End
:[A]</langsyntaxhighlight>
===Using nCr Function===
<langsyntaxhighlight lang="ti83b">PROGRAM:PASCALTR
:Lbl IN
:ClrHome
Line 5,721 ⟶ 6,035:
:End
:End
:[A]</langsyntaxhighlight>
 
=={{header|Turing}}==
 
<langsyntaxhighlight lang="turing">proc pascal (n : int)
for i : 0 .. n
var c := 1
Line 5,736 ⟶ 6,050:
end pascal
 
pascal(5)</langsyntaxhighlight>
 
Output:
Line 5,748 ⟶ 6,062:
== {{header|TypeScript}} ==
{{trans|XPL0}}
<langsyntaxhighlight lang="javascript">// Pascal's triangle
 
function pascal(n: number): void {
Line 5,779 ⟶ 6,093:
pascal(13);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,798 ⟶ 6,112:
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Input "Number Of Rows: "; N
@(1) = 1
Print Tab((N+1)*3);"1"
Line 5,811 ⟶ 6,125:
 
Print
End</langsyntaxhighlight>
Output:
<pre>Number Of Rows: 10
Line 5,831 ⟶ 6,145:
{{works with|Bourne Again SHell}}
Any n <= 1 will print the "1" row.
<langsyntaxhighlight lang="bash">#! /bin/bash
pascal() {
local -i n=${1:-1}
Line 5,848 ⟶ 6,162:
fi
}
pascal "$1"</langsyntaxhighlight>
 
=={{header|Ursala}}==
Zero maps to the empty list. Negatives are inexpressible.
This solution uses a library function for binomial coefficients.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
pascal = choose**ziDS+ iota*t+ iota+ successor</langsyntaxhighlight>
This solution uses direct summation. The algorithm is to
insert zero at the head of a list (initially the unit list <1>), zip it with its reversal,
map the sum over the list of pairs, iterate n times, and return the trace.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
pascal "n" = (next"n" sum*NiCixp) <1></langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %nLL
 
example = pascal 10</langsyntaxhighlight>
{{Out}}
<pre><
Line 5,882 ⟶ 6,196:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Base 1
Private Sub pascal_triangle(n As Integer)
Dim odd() As String
Line 5,911 ⟶ 6,225:
Public Sub main()
pascal_triangle 13
End Sub</langsyntaxhighlight>{{out}}
<pre> 1
1 1
Line 5,928 ⟶ 6,242:
=={{header|VBScript}}==
Derived from the BASIC version.
<langsyntaxhighlight lang="vb">Pascal_Triangle(WScript.Arguments(0))
Function Pascal_Triangle(n)
Dim values(100)
Line 5,941 ⟶ 6,255:
WScript.StdOut.WriteLine
Next
End Function</langsyntaxhighlight>
{{out}}
Invoke from a command line.
Line 5,962 ⟶ 6,276:
For example, if #99 contains value 2, then #@99 accesses contents of numeric register #2.
 
<langsyntaxhighlight lang="vedit">#100 = Get_Num("Number of rows: ", STATLINE)
#0=0; #1=1
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1)
Line 5,974 ⟶ 6,288:
}
Ins_Newline
}</langsyntaxhighlight>
 
===Using binary coefficients===
{{trans|BASIC}}
<langsyntaxhighlight lang="vedit">#1 = Get_Num("Number of rows: ", STATLINE)
for (#2 = 0; #2 < #1; #2++) {
#3 = 1
Line 5,987 ⟶ 6,301:
}
Ins_Newline
}</langsyntaxhighlight>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
<langsyntaxhighlight lang="vb">Sub pascaltriangle()
'Pascal's triangle
Const m = 11
Line 6,008 ⟶ 6,322:
Next n
MsgBox ss, , "Pascal's triangle"
End Sub 'pascaltriangle</langsyntaxhighlight>
{{out}}
<pre>
Line 6,026 ⟶ 6,340:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System.Numerics
 
Module Module1
Line 6,067 ⟶ 6,381:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre> 1
Line 6,092 ⟶ 6,406:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|wrenWren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
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|
Line 6,112 ⟶ 6,415:
System.write(" " * (n-i-1))
for (j in 0..i) {
Fmt.write("$3d ", binomialInt.callbinomial(i, j))
}
System.print()
Line 6,118 ⟶ 6,421:
}
 
pascalTriangle.call(13)</langsyntaxhighlight>
 
{{out}}
Line 6,141 ⟶ 6,444:
{{works with|Windows}}
<b>uses:</b> io.inc - Macro library from SASM
<langsyntaxhighlight lang="asm">
%include "io.inc"
 
Line 6,220 ⟶ 6,523:
pop ecx
ret
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,235 ⟶ 6,538:
{{trans|GW-BASIC}}
{{works with|Windows XBasic}}
<langsyntaxhighlight lang="xbasic">
PROGRAM "pascal"
VERSION "0.0001"
Line 6,253 ⟶ 6,556:
END FUNCTION
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,267 ⟶ 6,570:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
proc Pascal(N); \Display the first N rows of Pascal's triangle
Line 6,288 ⟶ 6,591:
];
 
Pascal(13)</langsyntaxhighlight>
 
{{Out}}
Line 6,309 ⟶ 6,612:
=={{header|zkl}}==
{{trans|C}}
<langsyntaxhighlight lang="zkl">fcn pascalTriangle(n){ // n<=0-->""
foreach i in (n){
c := 1;
Line 6,321 ⟶ 6,624:
}
pascalTriangle(8);</langsyntaxhighlight>
{{out}}
<pre>
Line 6,337 ⟶ 6,640:
 
In edit mode insert:
<langsyntaxhighlight BASIClang="basic"> 10 INPUT "How many rows? ";n
15 IF n<1 THEN GO TO 210
20 DIM c(n)
Line 6,360 ⟶ 6,663:
180 LET c(i)=d(i)
190 NEXT i
200 NEXT r</langsyntaxhighlight>
 
Then in command mode (basically don't put a number in front):
<syntaxhighlight lang BASIC="basic">RUN</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits