# Print number triangle

Given a number N, output a NxN right angled triangle, where each row i is filled with numbers up to i.

Example

n = 0

(no output)

n = 4

1
1 2
1 2 3
1 2 3 4


n = 10

1
1 2
1 2 3
.
.
.
1 2 3 4 5 6 7 8 9 10


(no alignment needed)

n = N

1
1 2
1 2 3
.
.
.
1 2 3 4 .... N


There is no trailing space at the end of each line.

Least number of bytes wins, and standard loopholes are not allowed.

• Can the output be a nested list of numbers? Commented Mar 12, 2015 at 5:39
• What should be the behavior for n=0, and for n>9? Commented Mar 12, 2015 at 18:55
• @Sieg Sure, as long as the output is correct. Commented Mar 13, 2015 at 0:57
• @freekvd for 0 there is no output, for n>9 no special formatting required Commented Mar 13, 2015 at 1:00
• Ah darn, you broke my submission. Fixing ASAP Commented Mar 13, 2015 at 5:54

# Mathematica, 32

Print@Row[Range@i," "]~Do~{i,#}&

• How about TableForm[Range/@Range@#]&? Commented Mar 21, 2015 at 15:13
• Shorter: Grid[Range/@Range@#]& Commented Mar 21, 2015 at 15:22
• And it even looks better. :) (I keep forgetting about Grid.) Commented Mar 21, 2015 at 15:23
• But I'm not sure if there is no trailing space at the end of each line. Commented Mar 21, 2015 at 15:24
• Oh good point. :( Commented Mar 21, 2015 at 15:25

# Scala, 7365 62 bytes

(n:Int)=>print(1 to n map(1 to _ mkString " ") mkString "\n")


Ungolfed

def printNumberTriangle(n: Int): Unit = {
def rowString(m: Int): String = 1.to(m).mkString(" ")
print(1.to(n).map(rowString).mkString("\n"))
}


# JavaScript, 73

n=5;for(i=1,s='';i<=n;i++)for(j=1;j<=i;j++)s+=j+(j==i?"\n":' ');alert(s);


### Excel VBA, 97 bytes

n = InputBox("n")
For i = n To 1 Step -1
For j = n To 1 Step -1
Cells(i, j) = j
Next j
n = n - 1
Next i


When executed you are prompted for n and the resulting triangles are displayed on the spread sheet:

• Optimized version to taking autoformatting into account, 74 Bytes Sub f(n) For i=n To 1 Step -1 For j=1To n Cells(i, j)=j Next j n=n-1 Next i End Sub Commented Mar 25, 2017 at 20:12

C,88 bytes

f(n,i,j,t){i=j=1;for(;i<=n;){t=j;printf("%d%c",t,j==i?(++i&&(j=1))*'\n':(++j||1)*' ');}}


Usage:

f(10);

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10


# JavaScript, 92 bytes

var x=function(o){for(var r=1;o>=r;r++){for(var a="",f=1;r>=f;f++)a+=f+" ";console.log(a)}};


usage: x(5)

• Welcome to PPCG! I think you accidentally put a stray  in there. Also, unnamed functions are generally allowed, so you can omit the var x. Even if not, you could shorten it to function x(o).... If you'd use the ES6 standard, you could shorten it even further by using arrow notation. You can also leave out all the vars ... we don't care about good style here. ;) Commented Sep 30, 2015 at 15:01
• @MartinBüttner Thank you for the good pointers :) Commented Sep 30, 2015 at 21:15

# awk, 27 bytes

{for(n=$0;n>=$i=++i;)print}


Got it working with some tweaks.

### Example usage and output

me@home:~$echo 0 | awk '{for(n=$0;n>=$i=++i;)print}' me@home:~$ echo 1 | awk '{for(n=$0;n>=$i=++i;)print}'
1
me@home:~$echo 2 | awk '{for(n=$0;n>=$i=++i;)print}' 1 1 2 me@home:~$ echo 12 | awk '{for(n=$0;n>=$i=++i;)print}'
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10 11 12


# Perl 6, 24 bytes

{say ~$_ for [\,] 1..$_}


# J, 14 bytes

":@>@<@:>:\@i.


Usage:

   f =. ":@>@<@:>:\@i.
f 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5


Explanation:

   i.4                      N.B.  i.n = list of numbers up to n
0 1 2 3

>:@i.4                   N.B.  >:n = increment n
1 2 3 4

>:\@i.4                  N.B.  >:\n = increment prefixes of n
1 0 0 0
1 2 0 0
1 2 3 0
1 2 3 4

<@:>:\@i.4               N.B.   < = Box, <@:>:\ = Box the incremented prefixes of n
+-+---+-----+-------+
|1|1 2|1 2 3|1 2 3 4|
+-+---+-----+-------+

":@>@<@:>:\@i.4          N.B.   ":@> = String format each opened box (ensures no zeros or spaces appear at the end of each line).
1
1 2
1 2 3
1 2 3 4


# C++, 130 bytes

To provide N, provide that many arguments on the command-line (the arguments don't matter, just the count of arguments).

#include <stdio.h>
#define printf P
int main(int c, char**){if(int x=c-1){main(x--,0);P("1");for(;x;--x){P(" %d",c-x);}P("\n");}}


# Jelly, 3 bytes

RRG


How it works:

RRG
R     Inclusive Range, 3 -> [1, 2, 3]
R    Inclusive Range for all elements, [1, 2, 3] -> [[1], [1, 2], [1, 2, 3]]
G   Attempt to format as grid


Try it online!

# tcl, 76

time {set p "";set j 1;while \$j<=[incr i] {set p$p\ $j;incr j};puts$p} $n  Testable on http://rextester.com/FPJXC1708 Is the first line accountable? It is not part of the algorithm, only serves for acquiring input. # Forth (gforth), 40 bytes : f 1+ 1 do i 1+ 1 do i . loop cr loop ;  Try it online! # Noether, 39 bytes I~A{A0>}{A(i1+~i(j1+~jP" "P£)" "P0~ji)}  Try it here! Explanation: I~A - Push User Input onto the stack and store in variable A {A0>} - If A>0 { - Then do A( - loop until top of stack equals A i1+~i - Increment i ( - loop until top of stack equals i j1+~j - Increment j P - Print top of stack (j) " " - Push the string " " onto stack P - Print top of stack (" ") £ - Pop top of stack ) - End loop "\n" - Push the string "\n" onto stack P - Print top of stack 0~j - Set variable j to zero i - Push i onto stack ) - End loop  # Pushy, 4 bytes :Lh_  Try it online! This works by building the stack up to the final line, step-by-step, and printing the stages: : \ Input times do (this consumes input): Lh \ Push stack length + 1 _ \ Print stack items, space separated.  # Vyxalj, 4 bytes ɾɾvṄ  Try it Online! ### Explained ɾɾvṄ rr # range over range over input v # vectorise Ṅ # join list by spaces  j flag joins by newlines # Arturo, 30 bytes $=>[loop map&=>[@1..&]=>print]


Try it!

# C++

int main()
{
cout << "Enter N:";
int N;
cin >> N;

for(int i=1; i <= N; i++)
{
for(int j=1; j<=i; j++)
{
cout << j;
}
cout << endl;
}

return 0;
}

• Btw, this is code-golf (writing a program in the least amount of characters). Therefore something like cout << "Enter N:"; is not necessary. Also you can save a lot of chars, if you remove the whitespace, remove return 0;, ... Commented Mar 12, 2015 at 11:33

Javascript, 83

n=9;r='';for(i=1;i<n+2;i++){for(a=1;a<i;a++){r+=a+' '}r=r.slice(0,-1)+'\n'}alert(r)


Pretty straight forwards

r=''; so javascript doesn't add the value as numbers

r.slice(0,-1)+'\n'remove last space and add a line end

Edit: info

First I was trying to use A030512(int seq) but that failed n>10

# Ruby - 51

r=->(n){(1..n).each{|i|puts (1..i).to_a.join(" ")}}


Sample output:

r[5] # 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5

r[7] # 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5
# 1 2 3 4 5 6
# 1 2 3 4 5 6 7

• If you aren't pedantic enough to care, trim 3 bytes by changing puts to p - but this surrounds every line in the output with " Commented Mar 12, 2015 at 15:21

Python 2 - 60 61 53 bytes

k='1'
for i in range(2,input()+2):print k;k+=' '+i


With thanks to Sp3000

• Had the indents in my code, lost them when I copied it to the post. And thanks for the suggestion! Commented Mar 12, 2015 at 13:26
• Also one more thing: by default, code golf implies full program or function, so you can't assume N is already defined (maybe i<=input()?). On a side note though, you can save a few bytes by replacing str(i) with <backtick>i<backtick> :) Commented Mar 12, 2015 at 13:40
• @Sp3000 \i\ seems to work: i. Commented Mar 12, 2015 at 14:51
• @user23013 i. Ah thanks, so it does. Commented Mar 12, 2015 at 14:53

# And the loser is... Pascal! 178 148 bytes

Sidenote: this isn't golfed at all, besides newlines and spaces. I haven't coded in Pascal for more than 10 years, so I used it just for the memories.

Golfed:

program p;procedure p(n:integer);var i,j:integer;begin for i:=1 to n do begin for j:=1 to i do begin write(j); end; writeln; end end;begin p(5);end.


Ungolfed:

program p;
procedure p(n:integer);
var i,j:integer;
begin
for i:=1 to n do begin
for j:=1 to i do begin
write(j);
end;
writeln;
end
end;
begin
p(5);
end.

• It doesn't seem to output the spaces. Also there is no need for semicolons before end. Commented Mar 13, 2015 at 9:34
• Right... the spaces. I didn't remember that semicolons before end were optional, two extra bytes could be golfed there
– jmm
Commented Mar 13, 2015 at 12:38

# k, 8

1+!:'1+!


I need to add 27 characters so I'm just going to type some nonsense here.

k)!5
0 1 2 3 4

k)1+!5
1 2 3 4 5

k)!:'1+!5
,0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

k)1+!:'1+!5
,1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

• Wouldn't a brief explanation be a lot more fun than some nonsense? Commented Mar 12, 2015 at 21:41

Golfscript - 41 chars

"#{STDIN.gets}"~.0={}{)}if,{,{)}%" "*}%n*


How it works:

"#{STDIN.gets}" -> Read a string from input

"~" -> Evaluate the input

".0=" -> Create a clone of the input and check if it's zero

"{}{)}if" -> If it's zero, do nothing, else add one to the number

",{,{)}%" "*}%" -> Create a list from 0 to N, loop through it and create new lists and do other stuff that I don't have time to explain.

"n*" -> Display it nicely

# ARM assembly 485 bytes

.global main
main:
mov r0, #10
mov r1, #1
bl triangle

mov r0, #10
bl putchar

mov r7, #1
swi 0

triangle:
cmp r1, r0
movgt pc, lr
push {r0,r1,lr}
mov r0, r1
mov r1, #1
bl row
mov r0, #10
bl putchar
pop {r0,r1,lr}
b triangle

row:
cmp r1, r0
movgt pc, lr
push {r0,r1,lr}
ldr r0, =numFormat
bl printf
pop {r0,r1,lr}
b row

numFormat:
.asciz "%d "


called using the subroutine triangle, register r0 holds the limit and r1 holds the starting value.

tested on Raspberry Pi and Android

# Java 8 - 293 chars

Golfed:

import java.util.stream.*;
import static java.util.stream.Collectors.joining;
public class T{public static void main(String[] a){int n=10;System.out.println(IntStream.range(1,n+1).boxed().map(i->IntStream.range(1,i+1).boxed().map(j->""+j).collect(joining(" "))).collect(joining("\n")));}}


Ungolfed:

    import java.util.stream.*;
import static java.util.stream.Collectors.joining;

public class T {
public static void main(String[] a){
int n=10;

System.out.println(
IntStream.range(1,n+1)
.boxed()
.map(i -> IntStream.range(1,i+1)
.boxed()
.map(j -> ""+j)
.collect(joining(" ")))
.collect(joining("\n")));
}
}


Example output, n = 10:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10


# PHP (65 bytes):

This is pretty simple to do in php:

for(;$i++<$_GET[n];$_[]=join(' ',range(1,$i)));echo@join('
',$_);  This probably may output an empty string or the '\0' char or worst if you use 0 (there is no control on it). This is because $_ will be nullwhen you use 0 and PHP will output null (which may output any of the said before).

There is another aproach (61 bytes):

foreach(range(1,$_GET[n])as$v)echo join(' ',range(1,$v))." ";  But it can't handle the 0 in the expected way. # K, 17 bytes (0:" "/$1+!)'1+!


Doing this sort of formatted output isn't very convenient in K. I used the "join" form of / from k5 to join elements of each vector with spaces. Try it with oK.

A nice thing about this solution is that it is in "tacit" form, so there's no need to create a function wrapper. Just append the argument N and suppress the result with ;:

  (0:" "/$1+!)'1+!5; 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5  ## Dyalog APL, 11 characters Assumes ⎕IO←1. (⍕↑)⍤0 1⍨⍳⎕  • ⍕⍵⍵ represented as a string. • ⍺↑⍵⍺ items taken from ⍵. • ⍺(⍕↑)⍵⍺ items taken from ⍵, the result represented as a string. • ⍺(⍕↑)⍤0 1⍵ – The previous expression, but executed for each item in ⍺ and each vector in ⍵. • (⍕↑)⍤0 1⍨⍵ – The previous expression with both arguments taken from ⍵. • (⍕↑)⍤0 1⍨⍳⍵ – The previous expression applied to the integers from 1 to ⍵. • (⍕↑)⍤0 1⍨⍳⎕ – The previous expression with input taken from the user. Powershell v2 number of Characters : 567  function Build-Triangle { [CmdletBinding()] param( [Parameter(Mandatory=$True,ValueFromPipeline=$True)] [int]$n
)

begin {}
process
{
[int]$cnt = 1 if ($n -gt 0 )
{
while ( $cnt -le$n )
{
$string +=$cnt.ToString() + " "
Write-Output -InputObject $string$cnt++
}
}
}
end {}
}

Build-Triangle -n 10 | Measure-Object
0 | Build-Triangle
11 | Build-Triangle
# just for kicks make the triangle upside down
11 | Build-Triangle  | Sort-Object -Descending
# find out how big the function is
Get-Content Function:\Build-Triangle | Measure-Object -Word -Character -Line
`
• Welcome to PPCG! This is code golf. Please show some effort to reduce the number of bytes in your code (single-letter variable names, no comments, no unnecessary whitespace would be a start). Commented Mar 18, 2015 at 3:26