# 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

# 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


## 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:

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


# 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, 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 # 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) # 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. # Elixir, 81 bytes &Enum.reduce(Enum.to_list(1..&1),"",fn(x,r)->r<>String.duplicate("*",x)<>"\n"end)  Anonymous function using the capture operator. Enum.reduce will iterate a list (the list is obtained by calling Enum.to_list on the range 1..n) and concatenate the return string r (which has been initialized with "") with a string made of x asterisks and a newline. Full program with test case: s=&Enum.reduce(Enum.to_list(1..&1),"",fn(x,r)->r<>String.duplicate("*",x)<>"\n"end) IO.write s.(5)  Try it online on ElixirPlayground ! # Pyth, 10 8 Bytes thanks to Jakube for helping me shave off the extra 2 bytes! VQ*Np"*"  Try it • FNU is the same thing as V. And you don't need that p, printing is implicit. – Jakube Oct 11 '16 at 15:54 • without the p the code doesn't execute properly. It would print one less level than it should. – Connor D Oct 13 '16 at 16:39 Since the course is taught in C++, I'm eager to see solutions in C++. # C++, 123 bytes, Non-competing (the joke here is to deliver a 'pure' c++ answer) #include<string> class X:public std::string{public:X(int i):std::string(i*(i+1)/2,'*'){for(;i--;)insert(i*(i+1)/2,"\n");}};  Test Brainfuck, 129 bytes I know there's already a shorter answer in brainfuck, however I wanted to create a program which could handle a multi-digit number input rather than either a single-digit input or a single ascii character input unlike the previous one posted. ,[>+++[->++++[-<<---->>]<]+>,]<-<<[<<]>>[<[->>++++++++++<<]>>>]+>>++++++++++>>++++++[-<+++++++>]<<<<<[>[->+>>.<<<]>>.<[-<+>]<+<-]  This is my first ever brainfuck program and it will work for any input between 0 and the maximum size of a single cell (traditionally 8 bits or 255) entered using the characters '0' to '9' (corresponding to ascii-values 048-057) Explanation The first part of this program, ,[>+++[->++++[-<<---->>]<]+>,], takes the input numbers as char values and removes 48 from each to make them equal to the numbers 0 to 9 rather than the char values of the numbers 0 to 9. It stores these in separate cells with a 1 in between each of them so that the start and end points can be found again. The second part, <-<<[<<]>>[<[->>++++++++++<<]>>>], consolidates the separate values into one cell. This is why the maximum size of a cell controls how high a number can be. The third section, +>>++++++++++>>++++++[-<+++++++>]<<<<<, is used to set up the other cells needed: one with the number of asterisks per line, one with the code for a linefeed and one with the code for an asterisk. There is also a blank cell left for working with later. The remainder of the code, [>[->+>>.<<<]>>.<[-<+>]<+<-], is used to: 1. Output as many asterisks as necessary 2. Output a linefeed 3. Reset the value of the cell controlling the asterisks 4. Increment the control cell 5. Decrement the cell with the number until it equals 0 # 05AB1E, 11 bytes '*×.pD¦r»  Try it online! Explanation: (Prints hourglass)  Implicit input - 5 '* Asterisk character - stack = '*' × Repeat input times - stack = '*****' .p Get prefixes - stack = ['*', '**', '***', '****', '*****'] D Duplicate last element STACK = ['*', '**', '***', '****', '*****'] , ['*', '**', '***', '****', '*****'] ¦ Remove first element from final list STACK = ['*', '**', '***', '****', '*****'] , ['**', '***', '****', '*****'] r Reverse 1 list and flatten both STACK = '*****','****','***','**','*','**','***','****','*****' » Join by newlines and implicitly print  For input 5, prints: ***** **** *** ** * ** *** **** *****  # C++ 11, 65 bytes Not including the include in the byte count. #include<string> using S=std::string;S g(int n){return n?g(n-1)+S(n,'*')+'\n':"";}  Usage: std::cout << g(n) << std::endl;  # SQL, 153 Bytes Golfed: CREATE PROCEDURE P @n INT AS BEGIN DECLARE @a INT;SET @a=0;DECLARE @o VARCHAR(1000);SET @o='*'WHILE @a<@n BEGIN PRINT @o;SET @o=@o+'*'SET @a=@a+1;END;END  Ungolfed: CREATE PROCEDURE P @n INT AS BEGIN DECLARE @a INT; SET @a=0; DECLARE @o VARCHAR(1000); SET @o='*' WHILE @a<@n BEGIN PRINT @o; SET @o=@o+'*' SET @a=@a+1; END; END  Testing: EXEC P '6'  Output: * ** *** **** ***** ******  • Wow, that's awesome! :-) – Sickboy Oct 27 '16 at 7:41 • @Sickboy thanks! :) My language of choice is normally C#, but someone beat me to it! :) – Pete Arden Oct 27 '16 at 9:22 • just @ is also a legal variable name in SQL, might save a couple of bytes there, and you can set the variable values directly in the DECLARE like so DECLARE @a INT=0 and a lot of those ; are unnecessary – grabthefish Feb 20 '17 at 14:31 • also VARCHAR(MAX) is 1 shorter – grabthefish Feb 20 '17 at 14:33 # Crystal, 31 bytes n=5;(1..n).each{|x|puts "*"*x} Output: * ** *** **** *****  Really demonstrates the beauty of Crystal/Ruby. n is the integer input, (1..n) is an inclusive range from 1 to n ([1, n]). .each is a method on Range that runs the provided block for every integer in the range. # Dip, 6 5 bytes **En  -1 byte thanks to Oliver Explanation: ** Push "*" repeated input times E Prefixes n Join by newlines  • 5-byte version: **En – Oliver Ni Oct 30 '16 at 16:55 # C, 88 bytes / 53 bytes Using C89. g(a){a&&g(a-1);a<2||puts("");while(a--)putchar('*');}main(int a,char**v){g(atoi(v[1]));} With whitespace for clarity: g(a) { a && g(a-1); a<2 || puts(""); while (a--) putchar('*'); } main(int a, char** v) { g(atoi(v[1])); }  Without main, this function is 53 bytes: g(a){a&&g(a-1);a<2||puts("");while(a--)putchar('*');} # python3, 58 57 bytes print('\n'.join(['*'*(p+1)for p in range(int(input()))]))  Ungolfed: rownums = int(input()) output = [] for i in range(rownums): currrow = "*" * (i+1) # 'i' * 5 == 'iiiii' output.append(currrow) print('\n'.join(output))  # SmileBASIC, 30 bytes INPUT N FOR I=1TO N?"*"*I NEXT  Haskell 36 Bytes Here is a version using map. f="*":map('*':)f;g=unlines.(takef)  Input g 10 Output "*\n**\n***\n****\n*****\n******\n*******\n********\n*********\n**********\n" Alternatives of interest might be: 38 Bytes g n=id=<<scanl(\x y->'*':x)"*\n"[2..n]  38 Bytes f="*\n":map('*':)f;g n=id=<<(ntakef)  36 g n=id=<<(take n$iterate('*':)"*\n")

• Anonymous functions are allowed, so you don't need the g=. – Laikoni Feb 11 '17 at 22:01

# k, 18 bytes

{-1@(1+!x)#\:"*";}


Explanation:

-1@ // prints to console

1+!x //returns list from 1 to x (implicit input)

#\:  //for each item in the prefixed list, "take" this many

"*" //asterisk string

• @ isn't necessary, and you can use ' instead of \: for -2 bytes {-1(1+!x)#'"*";} – Thaufeki Nov 4 '18 at 5:32

# Perl 6, 17 bytes

put(\*x++$)xx get  Full program that prints to stdout. How it works:  \* # a Capture object that stringifies to the asterisk, x # string-repeated by ++$         # a counter that starts at 1,
put(      )        # and printed followed by a newline.
xx get  # Do all of that n times.


Invokes the put statement n times, each time printing the asterisk repeated by the counter variable ++$. # Perl 6, 21 bytes {.put for \*Xx 1..$_}


A lambda that prints to stdout.
How it works:

{                   }  # A lambda.
\*           # A Capture object that stringifies to the asterisk.
1..$_ # Range from 1 to n. X # Cartesian product of the two, x # with the string repetition operator applied to each result. .put for # Iterate over the strings, and print each followed by a newline.  # Bash + Unix utilities, 26 bytes seq -f10^%f-1$1|bc|tr 9 *


Output to stderr should be ignored.

Try it online!

The code above works on TIO since the working directory there has no visible files. If this needs to run in a directory that contains a visible file, change * to \* at the cost of one byte (27 bytes):

seq -f10^%f-1 $1|bc|tr 9 \*  # Terrapin logo, 67 bytes to a :a make "b 1 repeat :a[repeat :b[type "*]make "b b+1 pr "] end  # PHP, 433431 28 bytes Note: uses IBM 850 encoding (old favorite reinvented recently) for(;$argn--;)echo$o.=~ı,~§;  Run like this: echo 5 | php -nR 'for(;$argn--;)echo$o.=~ı,~§;';echo > * > ** > *** > **** > *****  # Explanation Iterates from N down to 0. Add an asterisk to $o for each iteration, then outputs $o and a newline. # Tweaks • Add an asterisk to $o for each iteration, and then output $o. Saves 9 bytes • Combined adding an asterisk to $o with outputting, saves 3 bytes
• Saved 3 bytes by using $argn • @TheBitByte, does my answer qualify for your bounty? It yields an asterisk by binary negation of ı (in IBM-850 encoding, as noted) – aross Oct 17 '16 at 8:36 • Well, as long as it's an actual asterisk, then fine, it does qualify, however it is longer than some other bounty answers here. – Buffer Over Read Oct 19 '16 at 18:41 ## K, 16 Bytes  {-1(1+!x)#'"*"}; {-1(1+!x)#'"*"}10; * ** *** **** ***** ****** ******* ******** ********* **********  EDIT BELOW - adding explanation) /Code ---> explanation (pretend x is 3) 1+!x ---> Numbers from 1 to 3 1 2 3#"*" ---> Take left many items of right ==> ("*";"**";"***") -1x ---> Print x to the console, if x is a list, each item is printed to a new line example(notice the -1 printed at the bottom). -1("*";"**";"***") * ** *** -1 To silence the output(-1), put a semicolon after the expression e.g. -1("Hello"); Hello  # Röda 0.12, 30 29 bytes, non-competing h i{seq 1,i|{|j|print"*"*j}_}  This is my first try in this scripting language created by fergusq :D This is a function. To run, use this: h i{seq 1,i|{|j|print"*"*j}_} main { h(5) }  ### Ungolfed h i{ /* Define a function h with parameter i */ seq 1,i /* Generate a sequence of numbers from 1 to i */ |{ }_ /* and pipe it to a for-loop */ |j| /* where j is the number in the sequence*/ print"*"*j /* and print an asterisk duplicated j times*/ }  • The ; after the anonymous function parameter list is not actually required in Röda 0.12. It's a bug in the interpreter, but since you've specified the answer to be 0.12, I think you can remove it. I have been thinking that I may let the bug be, as its a handy feature in code golf, but haven't decided anything yet. – fergusq Mar 7 '17 at 13:32 • @fergusq Thanks for the tip! "It's not a bug, it's a feature!" – user41805 Mar 7 '17 at 14:38 • Why is this non-competing? – pppery Sep 25 '20 at 1:29 # Common Lisp, SBCL, 6966614544 41 bytes full program: (dotimes(i(read))(format t"~v{*~}* "i 1))  ### Explanation (dotimes(i(read)) <-- loop from i=0 to i=INPUT-1 (format t"~v{*~}* "i 1)) <-- loop, displaying i+1 asterisks per line  Ideas for improvement are welcomed. ## QBIC, 16 bytes :#*|[1,a|B=B+A?B  Explanation: : Gets a cmd line param as number called 'a' #*| Define A$ as '*'
[1,a|     FOR b = 1 to a
B=B+A     Extend B$with another astrix ?B Print B$
<FOR LOOP implicitly closed>


QBIC's seen a few updates since this answer was posted. This could now be done with these 12 bytes:

[:|B=B+@*?B