# Draw an asterisk triangle

Inspired by a task for programming 101 here's a task that hopefully isn't too easy or is a duplicate (kinda hard to search for things like this).

Input:

• A positive integer n >= 1.

Output:

• n lines of asterisks, where every new line has one asterisk more than the line before, and starting with one asterisk in the first line.

General rules:

• This is code-golf, so shortest answer in bytes wins.
• Since the course is taught in C++, I'm eager to see solutions in C++.

Test case (n=5):

*
**
***
****
*****

• Not duplicate, just subset of Generate a right triangle. – manatwork Oct 10 '16 at 12:20
• Training spaces allowed on each line? – Luis Mendo Oct 10 '16 at 12:33
• Is a trailing new line acceptable? – Fatalize Oct 10 '16 at 12:34
• Is a leading newline allowed? – Riley Oct 10 '16 at 14:38
• I don't see a reason why not. – Sickboy Oct 11 '16 at 11:35

# CJam, 1311 10 bytes

Thanks to @MartinEnder for removing two bytes, and @Linus for removing one more!

ri{)'**N}%


Try it online!

### Explanation

ri            e# Read input as an integer n
{     }%    e# Run this block for each k in [0 1 ... n-1]
)          e# Add 1 to the implicitly pushed k
'*        e# Push asterisk character
*       e# Repeat the character k+1 times
N      e# Push newline
e# Implicitly display

• You can use map on number without taking the range to save another byte. – Linus Oct 31 '16 at 17:27

# Pushy, 4 bytes

:42"


Try it online!

This method takes advantages of Pushy's automatic int/char conversion:

        \ Implicit: Input on stack
:       \ Input times do: (this consumes input)
42     \   Push 42 (char '*')
"    \   Print whole stack


Because each iteration adds a new * char, this outputs a triangle. For example, with n=4:

*       \   Stack: [42]
**      \   Stack: [42, 42]
***     \   Stack: [42, 42, 42]
****    \   Stack: [42, 42, 42, 42]


# LaTeX, 171 bytes

I had to use LaTeX instead of plain TeX for the \typein macro...

Here it is, as golfed as I could:

\documentclass{book}\begin{document}\typein[\n]{}\newcount\i\newcount\a\i=0\loop{\a=0\loop*\advance\a by1\ifnum\i>\a\repeat}

\ifnum\n>\i\repeat\enddocument


Explanation:

\documentclass{book}% Book because it is shorter than article ;)
\begin{document}% Mandatory...
\typein[\n]{}% User inputs \n
\newcount\i% Create a line counter
\newcount\a% And an asterisk counter
\i=0% Initializes the line number to zero
\loop{% Line number loop
\a=0% Sets the number of asterisks to zero
\loop% Asterisk loop
*% Prints the asterisk
\ifnum\i>\a% If the line number is smaller than the number of asterisks
\repeat% Then repeat
}% Otherwise prints a new line

\ifnum\n>\i% If input number is less than the number of lines then
\repeat% Repeat
\enddocument% And finish LaTeX


# Commodore 64/VIC-20 BASIC (and compatible C= 8-bits), ~77 tokenized BASIC bytes

0 INPUT"NUMBER OF *";A:ON-(A<1)GOTO1:J=1:FORI=1TOA:FORX=1TOJ:PRINT"*";:NEXTX:J=J+1:PRINT:NEXTI
1 :


Technically line 1 isn't required, but I'm mis-using the ON...GOTO command as a conditional GOTO in line zero so I added in the shortest possible line 1 to end it gracefully.

You will need to use Commodore keyword abbreviations to fit line zero on a C64, see the screen shot below (Note that the C128 in 128 mode might have different keyword abbreviations, but then you can enter more characters so you probably won't need it):

# Java 7 11, 8873 58 bytes

String c(int n){return(n<2?"":c(n-1)+"\n")+"*".repeat(n);}


-15 bytes by converting to Java 11.

Try it online. (NOTE: String#repeat(int) is emulated as repeat(String,int) for the same byte-count, because TIO doesn't contain Java 11 yet.)

Explanation:

String c(int n){          // Recursive method with integer parameter and String return-type
return(n<2?             //  If n is 1:
:                //  Else:
c(n-1)          //   Start with a recursive call with n-1
+"\n")    //   and a trailing new-line
+"*".repeat(n);} //  And append n amount of '*'


## Batch, 69 bytes

@set s=
@for /l %%i in (1,1,%1)do @call set s=*%%s%%&call echo %%s%%


# Ruby, 26 bytes

->n{s='';n.times{p s+=?*}}

• p will surround each line with double-quotes (because it calls inspect on its arguments). I can't speak for OP, but I suspect this disqualifies your answer. – Jordan Oct 10 '16 at 20:20

# Brainfuck, 70 bytes

,>++++++[<-------->>>+++++++<<-]<[>+[->+>.<<]>[-<+>]++++++++++.[-]<<-]


I'm sure this could be golfed a little bit. This version only works for single-digit numbers; feel free to modify it to work on larger numbers too.

Edit: If it's allowed to use a single character's ASCII value as the input, the resulting code is below. Only 60 bytes.

,>++++++[>>+++++++<<-]>[>+[->+>.<<]>[-<+>]++++++++++.[-]<<-]


Explanation:

,>++++++[<-------->>>+++++++<<-]  [this gets a single character from
input into the first cell, subtracts 48 to convert it to an integer
representation, and puts 42 in the 3rd cell (ASCII '*').]

<[ while the first cell is not zero do
>+   add 1 to 2nd cell (empty when we start)
[->+>.<<]  [while 2nd cell is not empty subtract 1 and print an *.
Make a copy in 3rd cell.]
>[-<+>]  copy 3rd cell value back to 2nd cell
++++++++++.[-] [put '\n' in 3rd cell, print, clear]
<<-
] loop


Edit: Here is a version that works for numbers up to 255, reading the text representation of the number followed by EOF. If your favorite interpreter has unbounded cells it will work up to 999.

>>,[----------
[
>++++++[<------>-]<--
>],]

[
Pointer is one past the end of a run of digits containing input.
Assumption: input < 256.
Add ten times most significant digit to second and ten times the
second to the third to get it in one cell.
]

<<<[>++++++++++<-]>[>++++++++++<-]>

Store 42 '*' in the cell 3 to the right
>>++++++[>+++++++<-]<<

[ While first cell is not empty
>+ Add 1 to 2nd cell
[->+>.<<] [make a copy in 3rd cell, print '*']
>[<+>-] copy 3rd back to 2nd
++++++++++.[-] print newline and clear 3rd
<<- subtract 1 from 1st and continue
]

• IIRC you can take a character as input and use its ascii code – acrolith Oct 10 '16 at 16:51
• Do you mean just use the input character to encode the number of rows in the triangle? Seems like it wouldn't work very well for small triangles since the low numbers are all control codes, not characters. – Sean McBane Oct 10 '16 at 18:09
• Yes, but your code would be smaller and I've seen other BF answers using that. – acrolith Oct 10 '16 at 19:08
• Where can I find the official rules for code golf on this site? – Sean McBane Oct 10 '16 at 19:44
• How is it that my Clojure solution is exactly as long as a BrainFuck answer? -_- – Carcigenicate Oct 10 '16 at 21:45

# Charcoal, 5 bytes

Ｇ↓→Ｎ*


It's the same length as Jelly, which is really bad for an ASCII-art oriented language. At least it's readable, I guess

### Explanation

Ｇ      Polygon
↓→     Down, then right
Ｎ   Input number
*  Fill with '*'


# Lua, 36 bytes

for i=1,...do print(("*"):rep(i))end


Takes input from the command line.

• How exactly you run it? I always get only an error: “lua5.3: IDid.lua:1: 'for' limit must be a number”. – manatwork Oct 13 '16 at 7:55
• @manatwork You can run it using e.g. lua IDid.lua 5 for 5 lines. – IDid Oct 13 '16 at 19:21
• Indeed. Thanks. No idea what I combined earlier. (Was before coffee…) – manatwork Oct 13 '16 at 19:30

unlines.(takeiterate('*':)"*")


The expression iterate('*':)"*" generates the infinite list ["*","**","***","****","*****",...]. The function then takes the first n elements and joins them with newlines.

The more direct

concat.(takeiterate('*':)"*\n")


is one byte longer.

# RProgN, 42 Bytes, Competing only for the Bounty

Q L c 's' =
►3'rep'º'R'=]¿]s\R\1-]} [


The length of the script is used as the character code for *.

Try it Online!

• Not sure if checking program length is borderline abusing the bounty rules or not... – Buffer Over Read Oct 14 '16 at 1:17
• You're gonna need to represent an asterisk one way or another. The only other way, other than to assign an ordinal through some complex method is to pull it from a constant previously defined in the language, which RProgN lacks. – ATaco Oct 14 '16 at 1:18
• Okay, I guess I'll get this one pass. Also, grabbing the asterisk from some predefined constant isn't allowed anyways. – Buffer Over Read Oct 14 '16 at 1:21

# Perl, 83 76 bytes (no asterisk)

print substr((split("\n",perldoc perlre))[55],48,1)x$_."\n"foreach(1..<>);  (Faster version for large input, 83 characters): $r=perldoc perlre;print substr((split("\n",$r))[425],11,1)x$_."\n"foreach(1..<>);


Explanation: The statement perldoc perlre executes the shell command to display the Perl documentation on regular expressions, which contains an asterisk as the 11th character on line 425. Split the resulting output by line, then extract that character and print in triangular format.

Edited to save 6 characters by not saving the output of the shell command, and instead just running it every time. It increases the runtime, though, but we only care about bytes, not runtime :) Another byte was saved (for a total of -7) by finding an earlier asterisk in the perldoc output.

• Very awesome way of doing it, wow. – Buffer Over Read Oct 19 '16 at 18:36

# ForceLang, 146 bytes

def S set
def G goto
S b 0
label 0
if a=b
G 1
if b
io.writeln()
S b 1+b
S c 0
label b
io.write "*"
S c 1+c
if b=c
G 0
G b
label 1


# Python 2, 38 37 bytes

There are only 36 characters shown, but a trailing newline is needed to avoid an EOF-related error raised by the interpreter. 1 byte knocked off for Flp.Tkc's observation.

for n in range(input()+1):print'*'*n


### Output for n=5

# leading newline here
*
**
***
****
*****


# Python 3, 45 bytes

The actual list comprehension is never assigned or printed, but if it were, it would be full of Nones, as None is the default return value of print().

[print('*'*n)for n in range(int(input())+1)]

• Why not just use range? – FlipTack Dec 23 '16 at 15:35
• Performance issues for very large triangles. range() in Python 2 returns a list containing all the integers, while xrange() returns a generator. I suppose for proof of concept range() does fine, but using xrange() when an actual list isn't necessary has become a habit for me. – James Murphy Dec 24 '16 at 5:56
• I know the difference. But this is code-golf :P – FlipTack Dec 24 '16 at 9:18

# TI-Basic, 28 22 bytes

Prompt A
"*
For(B,1,A
Disp Ans
Ans+"*
End

• Prompt A "* For(B,1,A Disp Ans Ans+"* End for 22 bytes – pizzapants184 Sep 17 '17 at 19:46
• Wow, I should have thought of that. Thanks @pizzapants184 – Timtech Sep 17 '17 at 20:48

-2 or -3 bytes thanks to @ØrjanJohansen

(
)((*)~*:S)^


Input is a Church numeral inserted between the ) and ^ on the second line. For example:

(
)((*)~*:S)::*:**^


If printing a leading newline is allowed, the following solution works by ommiting the ~, for 12 bytes:

(
)((*)*:S)^

• I think you can shorten this by two bytes by putting the newline in the starting string, or three (avoiding a ~) if an initial newline is permitted (the OP never completely clarified that.) – Ørjan Johansen Dec 29 '17 at 0:01
• @ØrjanJohansen Thanks, edited. – Esolanging Fruit Dec 29 '17 at 1:40

# R, 33 bytes

cat(strrep("*",1:scan()),sep="
")


Try it online!

I hope it's not a dupe - I was able to find only one other R answer. Leverages strrep and vectorization to build the vector "*","**",...,"******" and prints with cat using newline as a separator.

## Wn, 6 4 bytes

'**M


## Explanation

   M           % Map every item in the implicit input with...
% (There's an implicit range from 1)
'**            % asterisks input times

n % Join the result with a (n)ewline


# How do I use the n flag?

... W.py filename.w [input-list] n

## Pyke, 6 bytes

Voh\**


Try it here!

# Brain-Flak, 81 bytes

78 bytes but three for the -A flag, which enables ASCII output.

{(({}[()])<>()){({}[()]<(((((()()()){}())){}{}){})>)}{}((()()()()()){})<>}<>{}


Try it online!

Brain-flak isn't the greatest language for ASCII-art, but it still managed to be somewhat short. Ish. Kinda.

Explanation:

While True:
{

(
Decrement counter
({}[()])

And move copy to other stack
<>())

Push N '*'s
{({}[()]<(((((()()()){}())){}{}){})>)}

Pop 0
{}

Push newline
((()()()()()){})

Move back to counter
<>

Endwhile
}

Move to other stack
<>

Pop an extra newline
{}


## Actually, 8 bytes

R'**Mi


Try it online!

Explanation:

R'**Mi
R         range(1, n+1) ([1, 2, ..., n])
'**M   for each element: that many asterisks
i  flatten and implicitly print


## 5 bytes, non-competing

R'**i


Try it online!

This solution is non-competing because it relies on a bugfix released after this challenge was posted.

# RProgN, 41 Bytes.

24 of these bytes are just assigning R and s, so that we can use a spaceless segment.

'rep' º 'R' = '*' 's' = ►]¿]s\R\1-]}[


## Explination

'rep' º 'R' =       # Get the function for 'rep' (Replace), associate 'R' with it.
'*' 's' =           # Associate 's' with the string literal '*'
►                   # Begin spaceless segment.
]               # Push a copy of the top of the stack (The input)
¿               # While truthy, popping the top of the stack.
]           # Push a copy...
s \ R       # Push an *, swap the two top values giving "i, *, i", Repeat the *, i times, giving "i, ****", or whatever.
\ 1 -       # Swap the top values, giving "****, i", decrement the top value by 1.
]           # Push a copy of the top value.
}[              # End the while, after processing, pop the top value (Which would be 0). Implcititly print.


## Try it!

<style>
#frame{
width:60em;
height:60em;
border:none;
}
</style>
<iframe id='frame' src="https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=%27rep%27%20%C2%BA%20%27R%27%20%3D%20%27*%27%20%27s%27%20%3D%20%E2%96%BA%5D%C2%BF%5Ds%5CR%5C1-%5D%7D%5B&input=5">Sorry, You need to support IFrame. Why don't you..?</iframe>

## Racket 47 bytes

(for((i(+ 1 n)))(displayln(make-string i #\*)))


Ungolfed:

(define (f n)
(for ((i (+ 1 n)))                         ; (i 5) in 'for' produces 0,1,2,3,4
(displayln (make-string i #\*))))        ; #\* means character '*'


Testing:

(f 5)


Output:

*
**
***
****
*****


# Groovy, 27 characters

{1.upto(it){println"*"*it}}


Sample run:

groovy:000> ({1.upto(it){println"*"*it}})(5)
*
**
***
****
*****
===> null

• {x->(1..x).each{println"*"*it}} was the one I was about to post before seeing this... 31 vs 27, I always forget about upto and the implicit it closure. – Magic Octopus Urn Oct 12 '16 at 16:41
• @carusocomputing, yepp, I also usually forget about .upto, but this time IMP1's Ruby answer reminded it. – manatwork Oct 12 '16 at 16:58

# jq, 19 characters

(18 characters code + 1 character command line option.)

range(1;.+1)|"*"*.


Sample run:

bash-4.3$jq -r 'range(1;.+1)|"*"*.' <<< 5 * ** *** **** *****  On-line test (Passing -r through URL is not supported – check Raw Output yourself.) # Ruby, 27 (or 24) bytes (Thanks to m-chrzan for pointing out the miscounting.) Returns a string. ->n{(1..n).map{|i|?**i}*$/}


the map makes an array of strings of * of increasing length. The *$/ takes the array and joins the elements to make a newline-separated string. If an array of strings is acceptable, these three bytes can be saved, scoring 24. In test program f=->n{(1..n).map{|i|?**i}*$/}
puts f[5]

• I think arrays of strings are acceptable output by default. Also, I believe your current solution is only 27 bytes long, so it'll go down to 24 :D. – m-chrzan Oct 11 '16 at 12:07

# Java, 110 bytes

Not that short, but I really like having empty for loops.

String f(int n){String s="";for(int i=0;i<n;i++,s+=new String(new char[i]).replace("\0","*")+"\n"){}return s;}


# GameMaker Language, 68 bytes

a="*"for(i=2;i<=argument0;i++){a+="#"for(j=0;j<i;j++)a+="*"}return a


# Prolog, 60 58 56 bytes

g(N):-N<=0,put(*),g(N-1);!.
f(N):-N<=0,f(N-1),g(N),nl;!.


I'm not that familiar with Prolog, but I just gave it a shot. I'm sure it can be a lot shorter.

Put the code into a file, then load that file into swipl and run f(25). (or some other number).

EDIT: quotes can be left out in put statement
EDIT 2: changing =:= to <= saves 2 bytes. I tried inverting it, but that'd make it wait for a return for some reason.