[Question]
  [
Your task is to write a program or a function that prints an ASCII triangle. They look like this:
```
|\
| \
|  \
----
```
Your program will take a single numeric input `n`, with the constraints `0 <= n <= 1000`. The above triangle had a value of `n=3`. 
The ASCII triangle will have `n` backslashes (`\`) and vertical bars (`|`), `n+1` lines and dashes (`-`), and each line will have an amount of spaces equal to the line number (0-based, ie first line is line 0) besides the ultimate line.
## Examples:
Input:
```
4
```
Output:
```
|\
| \
|  \
|   \
-----
```
Input:
```
0
```
Output:
```
  
```
In this test case, the output must be empty. No whitespace.
Input:
```
1
```
Output:
```
|\
--
```
Input & output must be **exactly** how I specified.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so aim for the shortest code possible!
  
[Answer]
# C, 58 bytes
```
i;f(n){for(i=2*n;~i--;printf(i<n?"-":"|%*c\n",2*n-i,92));}
```
--
Thanks to @Steadybox who's comments on [this answer](https://codegolf.stackexchange.com/a/109512/16513) helped me shave a few bytes in my above solution
[Answer]
## Javascript (ES6), ~~97~~ ~~85~~ ~~81~~ ~~75~~ 74 bytes
```
n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)
```
Turns out I wasn't using nearly enough recursion
```
f=n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)
console.log(f(0))
console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~15~~ 16 bytes
Saved a byte thanks to *Adnan*
```
FðN×…|ÿ\}Dg'-×»?
```
[Try it online!](https://tio.run/nexus/05ab1e#ARsA5P//RsOwTsOX4oCmfMO/XH1EZyctw5fCuz///zQ "05AB1E – TIO Nexus")
**Explanation**
```
F       }         # for N in range [0 ... input-1]
 ðN×              # push <space> repeated N times
    …|ÿ\          # to the middle of the string "|\"
         Dg       # get length of last string pushed
           '-×    # repeat "-" that many times
              »   # join strings by newline
               ?  # print without newline
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~18~~ ~~17~~ 16 bytes
*1 byte saved thanks to @nmjcman101 for using another way of outputting nothing if the input is `0`*
```
é\é|ÀñÙá ñÒ-xÀ«D
```
[Try it online!](https://tio.run/nexus/v#@394ZczhlTWHGw5vPDzz8EIFIDVJt@Jww6HVLv///zcAAA "V – TIO Nexus")
Hexdump:
```
00000000: e95c e97c c0f1 d9e1 20f1 d22d 78c0 ab44  .\.|.... ..-x..D
```
### Explanation (outdated)
We first have a loop to check if the argument is `0`. If so, the code below executes (`|\` is written). Otherwise, nothing is written and the buffer is empty.
```
Àñ     ñ            " Argument times do:
  é\é|              " Write |\
      h             " Exit loop by creating a breaking error
```
Now that we got the top of the triangle, we need to create its body.
```
Àñ   ñ              " Argument times do:
  Ù                 " Duplicate line, the cursor comes down
   à<SPACE>         " Append a space
```
Now we got one extra line at the bottom of the buffer. This has to be replaced with `-`s.
```
Ó-                  " Replace every character with a -
   x                " Delete the extra '-'
```
---
This answer would be shorter if we could whatever we want for input `0`
# [V](https://github.com/DJMcMayhem/V), ~~14~~ 13 bytes
```
é\é|ÀñÙá ñÒ-x
```
[Try it online!](https://tio.run/nexus/v#@394ZczhlTWHGw5vPDzz8EIFIDVJt@L///8mAA "V – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
’⁶x⁾|\jṄµ€Ṫ”-ṁ
```
[Try it online!](https://tio.run/nexus/jelly#ASQA2///4oCZ4oG2eOKBvnxcauG5hMK14oKs4bmq4oCdLeG5gf///zQ "Jelly – TIO Nexus")
### How it works.
```
’⁶x⁾|\jṄµ€Ṫ”-ṁ  Main link. Argument: n
        µ       Combine the links to the left into a chain.
         €      Map the chain over [1, ..., n]; for each k:
’                 Decrement; yield k-1.
 ⁶x               Repeat the space character k-1 times, yielding a string.
   ⁾\j            Join the character array ['|', '\'], separating by those spaces.
      Ṅ           Print the result, followed by a linefeed.
         Ṫ      Tail; extract the last line.
                This will yield 0 if the array is empty.
          ⁾-ṁ   Mold the character '-' like that line (or 0), yielding a string
                of an equal amount of hyphen-minus characters.  
```
[Answer]
# C#, 93 bytes
```
n=>{var s=n>0?new string('-',n+1):"";while(n-->0)s="|"+new string(' ',n)+"\\\n"+s;return s;};
```
Anonymous function which returns the ASCII triangle as a string.
Full program with ungolfed, commented function and test cases:
```
using System;
class ASCIITriangles
{
    static void Main()
    {
      Func<int, string> f =
      n =>
      {
          // creates the triangle's bottom, made of dashes
          // or an empty string if n == 0
          var s = n > 0 ? new string('-', n + 1) : "";
          // a bottom to top process
          while ( n-- > 0)
          // that creates each precedent line
            s = "|" + new string(' ', n) + "\\\n" + s;
          // and returns the resulting ASCII art
          return s;
      };
      // test cases:
      Console.WriteLine(f(4));
      Console.WriteLine(f(0));
      Console.WriteLine(f(1));
    }
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 69 bytes
```
lambda x:'\n'.join(['|'+' '*n+'\\'for n in range(x)]+['-'*-~x*(x>0)])
```
[Try it online!](https://tio.run/nexus/python2#FcpBCsIwEAXQvaeY3Z8kbangqmAvkmSRopERnZZQIQvx6pG@9cvX0F7pvdwS1QlBMTxXUfb4woFg1SEE5LWQkiiVpI87VxOdRw/b/6rlOo8mmnYcOY7o9tnZTCfaiuhOmcU0P3bn7hL/ "Python 2 – TIO Nexus")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~24~~ ~~22~~ 21 bytes
*Saved 1 byte thanks to Martin Ender*
```
ri_{S*'|\'\N}%\_g+'-*
```
[Try it online!](https://tio.run/nexus/cjam#@1@UGV8drKVeE6Me41erGhOfrq2uq/X/vxEA "CJam – TIO Nexus")
**Explanation**
```
ri                     e# Take an integer from input
  _                    e# Duplicate it
   {                   e# Map the following to the range from 0 to input-1
    S*                 e#   Put that many spaces
      '|               e#   Put a pipe
        \              e#   Swap the spaces and the pipe
         '\            e#   Put a backslash
           N           e#   Put a newline
            }%         e# (end of map block)
              \        e# Swap the top two stack elements (bring input to the top)
               _g+     e# Add the input's signum to itself. Effectively this increments any 
                       e#  non-zero number and leaves zero as zero.
                  '-*  e# Put that many dashes
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~51~~ 67 bytes
```
param($n)if($n){1..$n|%{"|"+" "*--$_+"\"};write-host -n ('-'*++$n)}
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp5mZBiKrDfX0VPJqVKuVapS0lRSUtHR1VeK1lWKUaq3LizJLUnUz8otLFHTzFDTUddW1tLWBWmr///9vAgA "PowerShell – TIO Nexus")
*(Byte increase to account for no trailing newline)*
Takes input `$n` and verifies it is non-zero. Then loops to construct the triangle, and finishes with a line of `-`. Implicit `Write-Output` happens at program completion.
[Answer]
# bash + printf, 68 bytes
```
for((;i<$1;))
{
a=$a-
printf "|%$[i++]s\\\\\n"
}
[ $a ] && echo $a-
```
Use "bash *program\_name* *number*" to run. Sample run:
```
bash-4.1$ bash triangle 0
bash-4.1$ bash triangle 1
|\
--
bash-4.1$ bash triangle 2
|\
| \
---
bash-4.1$ bash triangle 3
|\
| \
|  \
----
```
[Answer]
# SmileBASIC, 51 bytes
```
INPUT N
FOR I=0TO N-1?"|";" "*I;"\
NEXT?"-"*(N+!!N)
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 39 bytes
```
.*
$*
*\`(?<=(.*)).
|$.1$* \¶
1
-
-$
--
```
[**Try it online**](https://tio.run/nexus/retina#@6@nxaWixaUVk6Bhb2OroaelqanHVaOiZ6iipRBzaBuXIZcul64Kl67u///GAA)
Convert decimal input to unary. Replace each `1` with `|<N-1 spaces>\¶`, print, and undo replace. Replace each `1` with a hyphen, and the last hyphen with 2 hyphens. Tadaa!
[Answer]
# Common Lisp, ~~89~~ 86 bytes
Creates an anonymous function that takes the n input and prints the triangle to `*standard-output*` (stdout, by default).
## Golfed
```
(lambda(n)(when(< 0 n)(dotimes(i n)(format t"|~v@t\\~%"i))(format t"~v,,,'-<~>"(1+ n))))
```
## Ungolfed
```
(lambda (n)
  (when (< 0 n)
    (dotimes (i n)
      (format t "|~v@t\\~%" i))
    (format t "~v,,,'-<~>" (1+ n))))
```
I'm sure I could make this shorter somehow.
[Answer]
## C ~~101~~ ~~93~~ 75 bytes
```
f(n){i;for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)prin‌​tf("-");}
```
Ungolfed version
```
void f(int n)
{
  int i;
  for(i=0;i++<n;)
    printf("|%*c\n",i,92);
  for(;n--+1;)
    printf("-");
}
```
@Steadybox Thanks for pointing out, makes a lot of sense.
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
```
f=lambda n,k=0:k<n and'|'+' '*k+'\\\n'+f(n,k+1)or'-'[:n]*-~n
```
[Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJCnk21rYJVtk6eQmJeiXqOura6grpWtrR4TE5Onrp2mAZTXNtTML1LXVY@2yovV0q3L@19QlJlXopGmYaKp@R8A "Python 3 – TIO Nexus")
Two more solutions with the same byte count.
```
f=lambda n,k=0:n and'|'+' '*k+'\\\n'+f(n-1,k+1)or-~k*'-'[:k]
f=lambda n,s='|':-~n*'-'[:n]if s[n:]else s+'\\\n'+f(n,s+' ')
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 98 bytes
```
256?dse1+d[q]st1=t^124*23562+dsaP2sk[[lkd256r^32*la+dsaPd1+skle>y]srle1<r]dsyx[45Ple1-dse0!>q]dsqx
```
[Try it online!](https://tio.run/nexus/dc#HYzLCoAgEAC/pWsStFt26vEL3sVAWiFQCt0O9eGdTTrOMExGOSzEDgTpaPiC6VoB@xo7OaAgtgrZax08lTCtHdbB/ppAsA9ufgyn4GBMhvi5dS9VoaYc22qOxcU7Z/keZ7PZbXcf "dc – TIO Nexus")
### Explanation
This takes due advantage of dc's `P` command, which utilizes conversion to base `256` on most systems. Therefore, for any input `n`, the program first raises `256` to the `n + 1`th power, multiplies the result by `124` (ASCII character `|`), and then adds `256*92+10=23562` to the product (where `92` is equivalent to the character `\` and `10` is the decimal value of the new-line (`\n`)). This results in a decimal number that when converted to base `256` with `P` results in the output `|\\n` where `\n` is the literal new-line character. A duplicate of this decimal number is also stored on top of register `a`.
Then, a "macro-loop" is invoked, as long as `n > 1`, in which a counter is incremented until `n`, beginning from `2`, and, as the 3rd through `n`th base `256` digits are unset, `256` is raised to each of those increments, a result which is then multiplied by `32` (the ASCII single space character). Then the value on top of register `a` is incremented by the resulting product, thus, on each iteration, setting each one of the unset base `256` digits in the between the `|` and the `\` characters to a single space.
Finally, after all `n-1` lines have been output, another "macro-loop" is invoked in which all the `n+1` dashes are output through the feeding of `45` to `P` on each iteration.
*Note:* The `[q]st1=t` segment makes sure that nothing is output for the input `0` by checking if the incremented input is equal to one, and if it is, simply executes the macro `[q]` which exits the program.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
Ｎβ¿β«↓β→⁺¹β↖↖β»
```
[Try it online!](https://tio.run/nexus/charcoal#@/9@z7pzmw7tB@LVj9omn9v0qG3So8Zdh3aCWNOACCix@/9/AwA "Charcoal – TIO Nexus")
## Breakdown
```
Ｎβ¿β«↓β→⁺¹β↖↖β»
Ｎβ               assign input to variable β
   ¿β«         »  if β != 0:
      ↓β           draw vertical line β bars long
        →⁺¹β       draw horizontal line β+1 dashes long
            ↖      move cursor up one line and left one character
             ↖β    draw diagonal line β slashes long
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 bytes
Saved 2 bytes thanks to @ETHproductions
```
o@'|+SpX +'\Ãp-pUÄ)·
```
[Try it online!](https://tio.run/nexus/japt#@5/voF6jHVwQoaCtHnO4@dB27SBtdd2C0MMt//@bAAA "Japt – TIO Nexus")
### Explanation
```
o@'|+SpX +'\Ãp-pUÄ)·
o                       // Creates a range from 0 to input
 @                      // Iterate through the array
  '|+                   // "|" + 
     SpX +              // S (" ") repeated X (index) times +
          '\Ã            // "\" }
             p-pU       // "-" repeated U (input) +1 times
                 Ä)·    // Join with newlines
```
[Answer]
# J, 20 bytes
*-13 bytes thanks to bob*
```
*#' \|-'{~3,~2,.=@i.
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/7WU1RVianTVq@uMdeqMdPRsHTL1/mtyKekpqKfZWqkr6CjUWimkFXNxpSZn5CukKRjCGKb/AQ "J – Try It Online")
## original: 33 bytes
```
(#&'| \'@(1,1,~])"0 i.),('-'#~>:)
```
### ungolfed
```
(#&'| \' @ (1,1,~])"0 i.) , ('-'#~>:)
```
[Try it online!](https://tio.run/##y/r/P81WT0FDWU29RiFG3UHDUMdQpy5WU8lAIVNPU0dDXVdduc7OSpMrNTkjXyFNweT/fwA "J – Try It Online")
[Answer]
# Commodore BASIC (C64/128, TheC64 & Mini, VIC-20, PET, C16/+4) - 46 BASIC Bytes
```
0inputn:ifnthenfori=1ton:?"{shift+B}{left}"spc(i)"{shift+M}":next:fori=.ton:print"-";:next
```
There is a sanity check for zero, but any other positive integer will work.
Note, a C64 has 25 rows and 40 columns text (some PETs and the C128 in VDC mode has 80 columns, the VIC-20 is 22 columns by 23 rows) so the output will be skewed if you exceed the screen limit in either direction.
I've added a screenshot so that you may see the PETSCII characters that I can't make happen in this listing.
[![Commodore C64 Triangle challenge](https://i.stack.imgur.com/eqgz8.png)](https://i.stack.imgur.com/eqgz8.png)
[Answer]
## Pyke, ~~18~~ 17 bytes
```
I Fd*\|R\\s)Qh\-*
```
[Try it here!](http://pyke.catbus.co.uk/?code=I+Fd%2a%5C%7CR%5C%5Cs%29Qh%5C-%2a&input=4)
[Answer]
# Python2, 73 bytes
```
n=input()
w=0
exec'print"|"+" "*w+"\\\\"+("\\n"+"-"*-~n)*(w>n-2);w+=1;'*n
```
A full program. I also tried string interpolation for the last line, but it turned out be a couple bytes longer :/
```
exec'print"|%s\\\\%s"%(" "*w,("\\n"+"-"*-~n)*(w>n-2));w+=1;'*n
```
Another solution at 73 bytes:
```
n=j=input()
exec'print"|"+" "*(n-j)+"\\\\"+("\\n"+"-"*-~n)*(j<2);j-=1;'*n
```
# Test cases
```
0:
1:
|\
--
2:
|\
| \
---
3:
|\
| \
|  \
----
6:
|\
| \
|  \
|   \
|    \
|     \
-------
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
```
?'\|- '2GXyYc!3Yc!)
```
[Try it online!](https://tio.run/nexus/matl#@2@vHlOjq6Bu5B5RGZmsaAzEmv//GwMA "MATL – TIO Nexus")
```
?         % Implicit input. If non-zero
  '\|- '  %   Push this string
  2       %   Push 2
  G       %   Push input
  Xy      %   Identity matrix of that size
  Yc      %   Prepend a column of 2's to that matrix
  !       %   Transpose
  3       %   Push 3
  Yc      %   Postpend a column of 3's to the matrix
  !       %   Transpose
  )       %   Index into string
          % Implicit end. Implicit display
```
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 41 bytes
```
:~a>0|[a|?@|`+space$(b-1)+@\`][a+1|Z=Z+@-
```
Explanation
```
:~a>0|  Gets a, and checks if a > 0
        If it isn't the program quits without printing anything
[a|     For b=1; b <= a; b++
?@|`+   Print "|"
space$  and a number of spaces
(b-1)   euqal to our current 1-based line - 1
+@\`    and a "\"
]       NEXT
[a+1|   FOR c=1; c <= a+1; c++
Z=Z+@-  Add a dash to Z$
        Z$ gets printed implicitly at the end of the program, if it holds anything
        The last string literal, IF and second FOR loop are closed implicitly.
```
[Answer]
## R, 101 bytes
```
for(i in 1:(n=scan())){stopifnot(n>0);cat("|",rep(" ",i-1),"\\\n",sep="")};cat("-",rep("-",n),sep="")
```
This code complies with the `n=0` test-case if you only consider `STDOUT` !  
Indeed, the `stopifnot(n>0)` part stops the script execution, displays nothing to `STDOUT` but writes `Error: n > 0 is not TRUE` to `SDTERR`.
**Ungolfed :**
```
for(i in 1:(n=scan()))
    {
    stopifnot(n>0)
    cat("|", rep(" ", i-1), "\\\n", sep = "")
    }
cat("-", rep("-", n), sep = "")
```
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
n=input();s='\\'
exec"print'|'+s;s=' '+s;"*n
if n:print'-'*-~n
```
[Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqioWldbKseE6POlVqRmqxUUJSZV6Jeo65dDBJWANFKWnlcmWkKeVYQOV11Ld26vP//TQA "Python 2 – TIO Nexus")
Prints line by line, each time adding another space before the backslash. If a function that doesn't print would be allowed, that would likely be shorter.
[Answer]
## JavaScript (ES6), 71 bytes
```
f=
n=>console.log(' '.repeat(n).replace(/./g,'|$`\\\n')+'-'.repeat(n+!!n))
```
```
<form onsubmit=f(+i.value);return!true><input id=i type=number><input type=submit value=Go!>
```
Outputs to the console. Save 6 bytes if printing to the SpiderMonkey JavaScript shell is acceptable. Save 13 bytes if returning the output is acceptable.
[Answer]
# Befunge-98, 68 bytes
```
&:!#@_000pv<
:kg00 ',|'<|`g00:p00+1g00,a,\'$,kg00
00:k+1g00-'<@,k+1g
```
[Answer]
# [Python 2](https://docs.python.org/2/), 67 bytes
Another function in Python 2, using `rjust`.
```
lambda n:('|'.join(map('\\\n'.rjust,range(n+2)))+'-'*-~n)[4:]*(n>0)
```
[Try it online!](https://tio.run/nexus/python2#DcIxDoMwDADAva/wZhsCohVTJPgIYQiiqYyKiULYqn497enC4Mrb78vqQS3hB9vtEKXdR0LnnGKbtuvMJnl9PUnrBzPX2GDVfJWn3s4V6dhxCUcCAdH/eGVie4OYRDMEEi5TZ@6mn38 "Python 2 – TIO Nexus")
[Answer]
# Perl, 63 bytes
```
$n=shift;print'|',$"x--$_,"\\\n"for 1..$n;print'-'x++$n,$/if$n
```
Ungolfed:
```
$ perl -MO=Deparse triangle.pl
$n = shift @ARGV;
print '|', $" x --$_, "\\\n" foreach (1 .. $n);
print '-' x ++$n, $/ if $n;
```
`$"` is the list separator, which defaults to " ". `$/` is the output record separator, which defaults to "\n". `$_` is the implicit loop variable.
]