# 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? – seequ Mar 12 '15 at 5:39
• What should be the behavior for n=0, and for n>9? – freekvd Mar 12 '15 at 18:55
• @Sieg Sure, as long as the output is correct. – Tan WS Mar 13 '15 at 0:57
• @freekvd for 0 there is no output, for n>9 no special formatting required – Tan WS Mar 13 '15 at 1:00
• Ah darn, you broke my submission. Fixing ASAP – seequ Mar 13 '15 at 5:54

# 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 – Taylor Scott Mar 25 '17 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. ;) – Martin Ender Sep 30 '15 at 15:01
• @MartinBüttner Thank you for the good pointers :) – Cristian Gutu Sep 30 '15 at 21:15

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


# Noether, 39 bytes

Non-competing: Noether is a new language

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


# 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, 2], [1, 2, 3]]
G   Attempt to format as grid


Try it online!

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. # 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;, ... – Jakube Mar 12 '15 at 11:33 Javascript, 83 Not to happpy about this one 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 # 1 # 1 2 # 1 2 3 # 1 2 3 4 # 1 2 3 4 5 r # 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 " – Devon Parsons Mar 12 '15 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! – SuchANovice Mar 12 '15 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> :) – Sp3000 Mar 12 '15 at 13:40 • @Sp3000 \i\ seems to work: i. – jimmy23013 Mar 12 '15 at 14:51 • @user23013 i. Ah thanks, so it does. – Sp3000 Mar 12 '15 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. – jimmy23013 Mar 13 '15 at 9:34 • Right... the spaces. I didn't remember that semicolons before end were optional, two extra bytes could be golfed there – jmm Mar 13 '15 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? – seequ Mar 12 '15 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} add r1, r1, #1 b triangle row: cmp r1, r0 movgt pc, lr push {r0,r1,lr} ldr r0, =numFormat bl printf pop {r0,r1,lr} add r1, r1, #1 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). – Martin Ender Mar 18 '15 at 3:26 ## C# - 92 bytes void f(int n){for(int i=0;i++<n;)Console.WriteLine(string.Join(" ",Enumerable.Range(1,i)));}  Nothing fancy, just a packed function. # JavaScript, 73 chars Not even trying to compare with the others here, just your typical first post: for(n=prompt(),i=1;n>=i;i++){var l="";for(j=1;j<=i;j++)l+=" "+j;alert(l)}  • I'm not sure this qualifies because it's alerting n times, which is not the same as outputting a 'right angle triangle' of the entire thing. – BadHorsie Mar 30 '15 at 16:22 Python 2 - 57 61 bytes Had another idea. Only bad thing is the leading space. def f(n): s='' for x in range(n):s+=' %s'%(x+1);print s[1:]  example output: >>> def f(n): ... s='' ... for x in range(n):s+=' %s'%(x+1);print s[1:] ... >>> f(8) 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  • Change print s to print s[1:]. This gets rid of the first char in the string – HEGX64 Mar 30 '15 at 7:42 # Element, 20 _'[1+2:'.2:\ ."\ ]  The main idea is that the stacks contain a string and a number. We repeatedly increment the number and append it to the string, printing the result. Given that Element has zero support for arrays, I think this is a very decent score. Since most people are probably unfamiliar with this language, Element is a golfing language I created in 2012. You can see the most updated interpreter, written in Perl, here. To make the explanation easier, I'll replace the newline with an L. _'[1+2:'.2:\ ."\L] _' input a number and put it onto the control stack [ ] this is a FOR loop 1+ increment the number. An empty stack is zero. 2: make a second copy of it ' put one copy on the control stack to save it . append the other copy to the end of the string 2: make a second copy of the new string  output one of them \ . append a space to the other " put the number from earlier pack onto the main stack \L output a newline, but the L should be an actual newline  # Python 2, 60 bytes One byte less than current best in Python 2, so I've decided to post it. def f(x): if x:f(x-1);print" ".join(map(str,range(1,x+1)))  Usage: f(5) 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5  Three slightly different approaches # Ruby, 37 bytes f=->n{n.times{|i|puts [*1..i+1]*" "}}  # Ruby, 38 bytes f=->n{puts (1..n).map{|i|[*1..i]*" "}}  # Ruby, 40 bytes f=->n{([*1..n+1]*" ").scan(/ /){puts$}}


## UniBasic 50 Bytes

S='';INPUT N;FOR I=1 TO N;S:=I;CRT S;S:=' ';NEXT I


Ungolfed:

S=''
INPUT N
FOR I=1 TO N
S:=I
CRT S
S:=' '
NEXT I