# 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

# Vitsy, 19 16 bytes

Yeah this needs some reducing. I'm out of practice!

D1H}\[\['*'O]aO]

(implicit input)
D                 Peek n, push n.
1                Push 1.
H               Pop x, pop y, push range(x, y)
}              Reverse, pop n, reverse, push n.
\[         ]  Pop n, do bracketed items n times.
\[    ]     Pop n, do bracketed items n times.
'*'O      Output the character *.
aO   Output a newline.


Think of it as though I'm iterating through a list (1 through n) and popping out the number of *s according to the currently selected list item.

Explanation soon.

• Is implicit input new for vitsy? – Conor O'Brien Oct 11 '16 at 0:30
• @ConorO'Brien Nope, that's been around since the beginning for numerical inputs through the command line. – Addison Crump Oct 11 '16 at 0:31
• Huh. My memory fails me, then. – Conor O'Brien Oct 11 '16 at 0:32

## Clojure, 59 bytes

#(doseq[m(range 1(inc %))](println(apply str(repeat m\*))))


Basically, just uses doseq to loop over the range, printing the corresponding number of stars.

It's really unfortunate that the shortest way I've been able to repeat a character in Clojure is (apply str (repeat m \*)). That's hardly competitive here. Some good ol' python string multiplication would have been awesome.

Ungolfed:

(defn tri [n]
(doseq [m (range 1 (inc n))]
(println (apply str (repeat m \*)))))


Should be fairly self-explanatory.

# Jolf, 7 bytes

This time, the builtin didn't let me win. Oh well.

―t0jj'*


Try it here!

## Explanation

―t0jj'*
―t0     pattern: left-corner-base triangle
j     with <input> height
j    and <input> width.
'*  comprised of asterisks


## Befunge93, 31 chars (3 spaces, 8 pure directionals)

&>:#v_@
-^  : >$55+,1 ,"*"<_^#:-1  ## Befunge98, 28 chars &>:#v_@ -^ : >$a,1
1,*'<_^#:-

• This prints the triangle upside down – Jo King Dec 29 '17 at 13:45
• The enemy's gate is down – Demur Rumed Jan 14 '18 at 15:45

# Java 7,72 70 bytes

Thanks to @kevin for shave it off by 2 bytes.

String f(int n,String s,String c){return n<1?c:f(--n,s+"*",c+s+"\n");}


### Output

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

• Nice approach, +1! Btw, you can golf it by 1 more byte by changing c+= to c+. – Kevin Cruijssen Oct 11 '16 at 8:41
• I see you've removed both s+= and c+=. I tried the same thing, but now your output is incorrect and contains a leading new line. The s+= should remain and c+= can be c+ for the same output without leading empty line. If OP allows leading newlines then it's of course fine like this. – Kevin Cruijssen Oct 11 '16 at 9:22

# Ruby, 32 bytes

1.upto($*.to_i){|i|puts"*"*i}  The $* is an array of arguments.

foo.rb 5 will print the following:

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

• Unless stated otherwise in the question, the answers should be full programs or functions. In both cases input and output should be handled properly either explicitly by the code itself, or implicitly by the interpreter, if it has such feature. You can not assume your code will find input data in some variable nor to just leave the result in a variable. As it is now, your code is considered a snippet, which is not a valid answer. – manatwork Oct 11 '16 at 9:42
• ARGV? Sure? Ruby 2.3.1 I use receives command line arguments as String, not Fixnum. – manatwork Oct 11 '16 at 9:51
• is the output of that okay? It's kinda implicit, but it is returned. – IMP1 Oct 11 '16 at 10:04
• If you ask me, is not valid. Katenkyo suggested in meta to allow such things as he claims Lua programs are able to return string. His suggestion received only 1 upvote and 1 downvote, so there is no consensus on that. In meantime I consider “Programs may output using their exit code... ... if and only if the challenge requires an integer as output, obviously.” relevant with 40 upvotes and 5 downvotes. – manatwork Oct 11 '16 at 10:19
• "Returning a string from a program" doesn't seem well-defined since it's in no way observable. You can fix your program at the cost of a single byte by using $><<"*"*i instead of "*"*i+$/ though. – Martin Ender Oct 11 '16 at 10:23

# Excel VBA, 109 bytes

This function returns to cell, requires text wrapping be turned on.

Function a(b)
For i = 1 To b
For c = 1 To i
d = "*" & d
Next c
a = a & d & Chr(10)
d = ""
Next i
End Function


99 Bytes - Alternative that runs as a function but prints to immediate.

Function f(b)
For i = 1 To b
For c = 1 To i
Debug.Print "*";
Next c
Debug.Print
Next i
End Function


94 Bytes - One more that is just a sub with hard coded value, prints to immediate.

Sub k()
r = 5
For i = 1 To r
For c = 1 To i
Debug.Print "*";
Next c
Debug.Print
Next i
End Sub


### PHP, 66 58 bytes

Just a simple loop, really.

I'm new to golfing, so might not be the shortest way.

for($i=fgets(STDIN);$x++<$i;)echo str_repeat("*",$x)."\n";


https://eval.in/658719

Thanks to manatwork for byte-saving.

• No need to explicitly initialize $x, so you can leave that out and move the initialization of$i in its place to spare 1 ; separator. And you can combine the loop's test with the loops stepping: for($i=fgets(STDIN);$x++<$i;)echo str_repeat("*",$x)."␤"; – manatwork Oct 11 '16 at 15:24

# Javascript, 71 bytes 48 Bytes, thanks ETHproductions!

(n,c)=>{while(c<=n)console.log("*".repeat(c++))}

• Welcome to PPCG! You don't need to call the function, just define it: (n,c)=>{while(c<=n){console.log("*".repeat(c++));}} is a valid entry. Also, you don't need the braces in the while loop, nor the semicolon at the end: (n,c)=>{while(c<=n)console.log("*".repeat(c++))} – ETHproductions Oct 11 '16 at 15:21

## Ruby, 29 bytes

->n{n.times{|i|puts'*'*i+?*}}


Call with ->n{n.times{|i|puts'*'*i+?*}}[number].

• No need for parenthesis around the proc parameter and is shorter to add a literal character than to add 1 to the multiplier ('*'*(i+1)'*'*i+?*). (BTW, you can call anonymous proc without assigning it to a variable: ->n{n.times{|i|puts'*'*i+?*}}.) – manatwork Oct 11 '16 at 9:49

# VBA, 84 bytes

taking advantage of recursive coding. it generates x times * as the line/round

Function f(x)
If x<=1 Then f="*" Else f=f(x-1) & vbCrLf & String(x,"*")
End Function


results:

?f(10)
*
**
***
****
*****
******
*******
********
*********
**********
?f(2)
*
**

?f(5)
*
**
***
****
*****


# C++, 78 bytes

I don't know how there are 2 C++ answers that don't just do it with for loops. Very short and sweet this way:

void T(int n){for(int i=1;i<=n;i++){for(int j=0;j<i;j++)cout<<'*';cout<<'\n';}}


## Full program

#include <iostream>

using namespace std;

void T(int n)
{
for(int i = 1; i <= n; i++)
{
for(int j = 0; j < i; j++)
cout << '*';
cout << '\n';
}
}

int main()
{
T(5);
}


Edit: it is unclear to me whether to count the #include<iostream>, using namespace std, and/or std::whatever in calls. C/C++ answers all over this site seem to use both, and for the most part no one seems to care except for the occasional comment. If I need the std::, then +10. If I need the #include<iostream>, +18 (although GCC allows me to do without the basic includes, so maybe not that one)

# Common Lisp (Lispworks), 71 bytes

(defun f(n)(dotimes(i n)(dotimes(j(1+ i))(format t"*"))(format t"~%")))


Usage:

CL-USER 170 > (f 5)
*
**
***
****
*****
NIL


Ungolfed:

(defun f (n)
(dotimes (i n)
(dotimes (j (1+ i))
(format t "*"))
(format t "~%")))


# MoonScript, 31 bytes

(n)->for i=1,n
print "*"\rep i


Sample call:

_ 5


F#, 114 chars

[<EntryPoint>]
let main a =
for i = 1 to System.Int32.Parse(a.) do
printfn "%s" <| String.replicate i "*"
0

• Welcome to the site! I don't know anything about F#, but it looks like you might be able to take away some of the whitespace? – DJMcMayhem Oct 13 '16 at 16:18
• Thanks! My first golf, both in my company and on the site. I did try and so far it looks like the other "type" of F# syntax is "verbose", which just gets longer. The indentation is the "light" syntax, which at minimum is a new line char and a space to indent. We do these in our slack channel but i didn't see any F# answers here, so i figured I would post! I can update with test cases but anyone can copy into a new F# console app and run pretty easily with VS 2015 Community and the F# tools, all of which are free. – magumbasauce Oct 13 '16 at 23:49

# Braingasm, 27 bytes

Braingasm is a brainfuck variant with just a few more instructions and options. And this task would've been so much easier if I had bothered implementing that as many times as the value in the current cell thing yet..

;[->+[->+42.<]10.>[-<+>]<<]


Here's how it works:

;                           Read an integer from stdin and write it to cell#1
[                        ] While the value of cell#1 is not zero,
->+                    <    substract one from cell#1 and add one to cell#2.
[->+   <]                Each time, do the same between cell#2 and cell#3,
42.                    but also print an asterix on the way.
10.             Then print a newline.
>[-<+>]<     Move the value from cell#3 back to cell#2


Python 3, 196 Bytes

import contextlib as b,io;q=io.StringIO()
with b.redirect_stdout(q):import this
n=int(input());c=q.getvalue();print(''.join([''.join([c for z in range(n)][:i+1])+'\n' for i in range(n)]))


This is probably counted as a cheat, but it uses the asterisk character in the import this string rather than explicitly writing an asterisk in the program code. It also doesn't use any asterisk multiplication operators. It temporarily rerouts stdout so as not to print the Zen of Python when run.

# 05AB1E, 8 bytes

TžQè×.p»


Explanation coming soon

# Scala, 44 30 bytes (51 45 without asterisk, 41 for hourglass)

## With asterisk in code (30 bytes):

(i:Int)=>(i to(1,-1))map("*"*) //create a range from i to 1 and map each number to that number of asterisks


## Without asterisk (45 bytes):

(i:Int)=>(i to(1,-1))map(((41+1).toChar+"")*) //same as above, but without a literal asterisk


## Without asterisk and easy ways of calculating 42 (57 bytes):

(i:Int)=>(i to(1,-1))map(((math sqrt("7G"##)).toChar+"")*)


## is the hashcode method, which returns 1764 for the string "7G", the square root of 1764 is 42, the ascii code for *

## Hourglass:

(& :Int)=>((&to(1,-1))++(2 to&))map("*"*)

(& :Int)=>        //define an anonymus function with an int parameter called &
(
(& to (1,-1))   //a range from & to 1, counting by -1, aka downwards
++              //concat
(2 to&)         //a range from 2 to &
)
map(              //map each number to
"*" *             //the string "*" repeated x times
)

• @TheBitByte You're right, I didn't notice that I've used asterisks for multiplication / string repitition. I just thought that I could replace '*' with (7*6).toChar and that's it. – corvus_192 Oct 14 '16 at 14:50
• The bounty spec is not really precise, it just states "other cheating methods". I have no idea what you consider cheating. – corvus_192 Oct 16 '16 at 18:15
• @TheBitByte What do you consider acceptable then? sqrt(1764)? Building a sequence of 42 ones and summing them? Using a string used somewhere in the standard library and extract an asterisk from it? – corvus_192 Oct 16 '16 at 18:39
• @TheBitByte It's your bounty, you can make the rules but you should precisely state what you allow and what you consider cheating. – corvus_192 Oct 16 '16 at 19:02
• @TheBitByte I know that scala can't win against all those golfing languages – corvus_192 Oct 16 '16 at 19:14

# Element, 16 bytes

_'[1+'[\*]\
"]


Try it online!

Explanation:

This is a pretty simple nested-loop approach. Let N represent the newline in the source code.

_'[1+'[\*]\N"]
_'                take input and move it to the control stack
[            ]  a FOR loop, each iteration = 1 line of output
[1+          ]  increment the top of the stack, as a counter
[  '         ]  move that value to the control stack
[   [   ]    ]  another FOR loop, for the current line
[   [\*]    ]  output a literal asterisk
[        \N ]  output a literal newline
[           "]  move the counter from control to main stack


# C++, 63 bytes

void s(int n){if(n)s(n-1),cout<<setfill('*')<<setw(n+1)<<"\n";}


Usage:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
s(5);
}


Overrides the filling character (which is usually a space), and outputs an empty string (or actually a newline).

One weird thing about this code is the usage of if (...) - I cannot find a way to replace it by a conditional operator ... ? ... : ....

# Swift 3, 86 bytes

for i in 1...Int(CommandLine.arguments)!{print(String(repeatElement("*",count:i)))}


Yuck. If I can drop the Int and String initializers I might be able to get this shorter than Java. Open to any optimizations.

Ungolfed:

import Foundation

guard CommandLine.argc > 1, let a = Int(CommandLine.arguments) else {
fatalError("Invalid or nonexistent argument")
}

for i in 1...a {
print(String(repeatElement("*", count: i)))
}


Usage:

➜ ~ swift asterisk.swift 5
*
**
***
****
*****


## ><>, 47 bytes

<v[1:$-1;!?:$+10
0\:&
$>:@=?v1+&:&"*"o 0f]oa~<.  Try it here! This was fun to write, though a bit more bytes than I expected. # Sinclair ZX81/Timex TS1000/1500, 117 bytes (listing) 1 PRINT "NUMBER OF * TO SHOW?" 2 INPUT A 3 IF A<1 THEN STOP 4 LET J=A/A 5 FOR I=1 TO A 6 FOR X=1 TO J 7 PRINT "*"; 8 NEXT X 9 LET J=J+1 10 PRINT 11 NEXT I  Note that because the screen scroll isn't handled in this program listing, you may only enter a number between 0 and 22 because as soon as the ZX81 hits the bottom of the screen it will halt the program. You can see the missing * by using CONT when this happens, but also note that the ZX81 only has 32 columns text by default in BASIC. • To save actual (system) bytes, you may amend the following lines: 3 IF A<CODE "{GRAPHICS ON}{SHIFT}1{SHIFT OFF}{GRAPHICS OFF}" 5 FOR I=PI/PI TO A 6 FOR X=PI/PI TO J 9 LET J=J+PI/PI – Shaun Bebbers Feb 27 '17 at 9:42 ## SQL, 80 bytes DECLARE @i INT=1,@ INT=5WHILE @i<>@ BEGIN PRINT REPLICATE('*',@i)SET @i=@i+1 END  ungolfed: DECLARE @index INT=1, @rows INT=5 WHILE @index<>@rows BEGIN PRINT REPLICATE('*',@index) SET @index=@index+1 END  # Rebol, 32 bytes loop do input[print append{}"*"]  Ungolfed: loop do input [ print append {} "*" ]  # AutoHotkey, 28 bytes Loop,%1% Send,{* %A_Index%}n  %1% is the first argument passed in %A_Index% is the current iteration in the loop Send sends a keystroke multiple times if it's followed by a number # dc, 33 bytes ?sa0[1+d1F6r^3C*1EF/PAPdla>x]dsxx  Input on stdin, output on stdout. Try it online! # Forte, 101 bytes 1INPUT0 2LET4=(0*(0+1))*5 4END 6PUT42:LET7=6+1 7LET6=6+10 8PUT10:LET9=((9+9)+14)-3:LET3=8+5 3LET8=9-1  Try it online! I've been wanting to try Forte for a while, and this seemed like a fine challenge for it. It was quite an effort writing the program, then golfing it and making it fit in one-digit numbered lines. It was also quite fun :) Kudos to ais523 for inventing this and many more incredible languages. Since I'm in the mood I'll write an explanation in details, covering also the basis of the language. ### Explanation First, a very brief introduction for those who don't know this language, you can find the full specification and guide on its esolang page. The syntax of Forte is similar BASIC, with line numbers prepended to each line, only that in Forte you dont GOTO 10, you make 10 come to you! With the command LET, you can assign a number to... another number. If the command LET 10=20 is executed, from now on every time the number 10 is referenced, directly or indirectly (5+5 counts too), it is replaced by 20 instead. This affects line numbers too, so if we were on line 19 when executing that instruction, the next line to be executed will be our old line 10, now line 20. Now, the actual code (with spaces added for clarity): 1 INPUT 0  This is practically LET 0=<a number taken from stdin>, in this program 0 is used like a variable, and only in line number 2 2 LET 4=(0*(0+1))*5 4 END  Line 4 is the one that terminates the program, so we want to put it at the position where we are done printing asterisks. How many of them do we need to print, though? As fitting for a "draw a triangle" challenge, the answer is given by triangular numbers! The formula to calculate the nth triangular number is n*(n+1)/2. We will print an asterisk every 10 lines, so we multiply it by 10 and get n*(n+1)*5. Use 0 instead of n, add parentheses for every operation (always mandatory in Forte), and you get line 2. 6 PUT 42:LET 7=6+1 7 LET 6=6+10  Here we print the asterisks. The ASCII code for * is 42, so you get what PUT 42 does. The colon separates multiple instructions on the same line, so we then execute LET 7=6+1. What use do we have in redefining 7 as 6+1? Isn't it the same thing? Let's see what happens next. Line 7 redefines 6 as 6+10, so 16. Ignoring for a moment the rest of the code, this means that when we reach line 16 we will print another asterisk, and then redefine 7 as 6+1. But now 6 is 16, so we are redefining it as 16+1! Line 7 is now line 17 and is the next one to be executed, changing 6 to 6+10, which means changing 16 to 16+10, so on line 26 we will print another asterisk, and so on. Since in Forte a line cannot change its own number, this is the simplest structure for a loop, two lines changing each other's numbers repeatedly. I know this can be quite confusing, but that's kind of the point of the whole language ;) 8 PUT 10:LET 9=((9+9)+14)-3:LET 3=8+5 3 LET 8=9-1  Ok, that line 3 put here may seem out of place, but in Forte line order doesn't matter, only line numbering. I've chosen to put this line at the end because this pair of lines forms again a cycle, redefining each other's numbers, so it's easier to see them together. Moreover, the first time line 3 is executed (when 3 is still equal to 3 and nothing else), it has no effect on the program, redefining 8 as 8. As you probably have guessed PUT 10 prints a newline, then the hard part comes. We want each line to have one more asterisk than the one before, so to know where to put the next newline we need to know where the previous one was. To do this, we use another "variable": the number 9. In practice, when we are about to print a newline on line 8, line 3 will be positioned (near) where the previous newline was printed, we'll use it to calculate where the next newline must be printed and move 9 (near) there. (Remember that line 8 can't move itself). Then we move line 3 a bit further than the current position, and use it to move line 8 to our 9. These three numbers (3,8, and 9) were chosen in order not to conflict with any other redefinition of a number, and to be easy to use together (since neither 5 nor 1 will ever be redefined by this program we can do LET 3=8+5 and LET 8=9-1). All of these numbers will always be redefined as themselves+10n. This means that 8 will only ever be redefined to numbers ending with an 8 (28,58,98...). This same property is valid for any other number redefinintion in this program (except 0), because this helped greatly my reasoning while writing the code (if you are crazy enough you can try to golf some bytes by using a smaller step, but I doubt there is much room for golfing without completely changing approach). So, the actual difficult part of this program: LET 9=((9+9)+14)-3. This operation can be better explained if expanded to LET 9=(9+(9-(3-4)))+10, where 4 and 10 represent their respective actual numerical values (in the code they are grouped as 14, 4 wouldn't actually be usable because it was redefined in line 2). As we said before 3 is still placed near the previous newline; we subtract 4 from it to get the previous position of 9 (if 3 is 63, our previous 9 was 59), then we compute the difference between the current and the previous 9 to know how many program-lines have passed since the last newline was printed. We add this value to the current 9, plus 10 because the next time we will want to print one more asterisk. Our 9 is now where we want to print the next newline, so we move 3 to the current position, it will then move 8 to where it's needed, just before 9. Phew, that was long. And hard. No dirty jokes, please ## Perl 6 (27) {.say for '*' <<x<<(1..$_)}
`