58
\$\begingroup\$

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

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

137 Answers 137

2
\$\begingroup\$

Pyth, 10 8 Bytes

thanks to Jakube for helping me shave off the extra 2 bytes!

VQ*Np"*"

Try it

\$\endgroup\$
  • \$\begingroup\$ FNU is the same thing as V. And you don't need that p, printing is implicit. \$\endgroup\$ – Jakube Oct 11 '16 at 15:54
  • \$\begingroup\$ without the p the code doesn't execute properly. It would print one less level than it should. \$\endgroup\$ – Connor D Oct 13 '16 at 16:39
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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:

*****
****
***
**
*
**
***
****
*****
\$\endgroup\$
2
\$\begingroup\$

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;
\$\endgroup\$
2
\$\begingroup\$

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:

*
**
***
****
*****
******
\$\endgroup\$
  • 1
    \$\begingroup\$ Wow, that's awesome! :-) \$\endgroup\$ – Sickboy Oct 27 '16 at 7:41
  • \$\begingroup\$ @Sickboy thanks! :) My language of choice is normally C#, but someone beat me to it! :) \$\endgroup\$ – Pete Arden Oct 27 '16 at 9:22
  • \$\begingroup\$ 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 \$\endgroup\$ – grabthefish Feb 20 '17 at 14:31
  • \$\begingroup\$ also VARCHAR(MAX) is 1 shorter \$\endgroup\$ – grabthefish Feb 20 '17 at 14:33
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Dip, 6 5 bytes

`**En

-1 byte thanks to Oliver

Explanation:

`**    Push "*" repeated input times
   E   Prefixes
    n  Join by newlines
\$\endgroup\$
  • \$\begingroup\$ 5-byte version: ``**En` \$\endgroup\$ – Oliver Ni Oct 30 '16 at 16:55
2
\$\begingroup\$

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('*');}

\$\endgroup\$
2
\$\begingroup\$

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))
\$\endgroup\$
2
\$\begingroup\$

SmileBASIC, 30 bytes

INPUT N
FOR I=1TO N?"*"*I
NEXT
\$\endgroup\$
2
\$\begingroup\$

Haskell 36 Bytes

Here is a version using map.

f="*":map('*':)f;g=unlines.(`take`f)

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=<<(n`take`f)

36

g n=id=<<(take n$iterate('*':)"*\n")
\$\endgroup\$
  • \$\begingroup\$ Anonymous functions are allowed, so you don't need the g=. \$\endgroup\$ – Laikoni Feb 11 '17 at 22:01
2
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ @ isn't necessary, and you can use ' instead of \: for -2 bytes {-1(1+!x)#'"*";} \$\endgroup\$ – Thaufeki Nov 4 '18 at 5:32
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

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 \*
\$\endgroup\$
2
\$\begingroup\$

Terrapin logo, 67 bytes

to a :a
make "b 1 repeat :a[repeat :b[type "*]make "b b+1 pr "]
end
\$\endgroup\$
2
\$\begingroup\$

PHP, 43 34 31 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
\$\endgroup\$
  • \$\begingroup\$ @TheBitByte, does my answer qualify for your bounty? It yields an asterisk by binary negation of ı (in IBM-850 encoding, as noted) \$\endgroup\$ – aross Oct 17 '16 at 8:36
  • \$\begingroup\$ Well, as long as it's an actual asterisk, then fine, it does qualify, however it is longer than some other bounty answers here. \$\endgroup\$ – Buffer Over Read Oct 19 '16 at 18:41
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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*/
}
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – fergusq Mar 7 '17 at 13:32
  • \$\begingroup\$ @fergusq Thanks for the tip! "It's not a bug, it's a feature!" \$\endgroup\$ – Kritixi Lithos Mar 7 '17 at 14:38
2
\$\begingroup\$

Common Lisp, SBCL, 69 66 61 45 44 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.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Excel VBA, 32 Bytes

Anonymous VBE immediate window function that takes input from range A1 and outputs to the VBE immediate window.

For i=1To[A1]:?String(i,42):Next
\$\endgroup\$
2
\$\begingroup\$

APL (Dyalog Unicode), 7 bytesSBCS

(,⍕⊢)⌸⍳

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Canvas, 3 bytes

*×]

Try it here!

Explanation:

  *×]  full program
{  ]  map over [1..input]
  *×      repeat by *
\$\endgroup\$
2
\$\begingroup\$

k, 16 12 bytes

4 bytes removed thanks to ngn! :)

{`0:,\x#"*"}

{          } /function(x)
      x#"*"  /reshape "*" by x
    ,\       /scan concatenation through the list
 `0:         /print line by line
\$\endgroup\$
  • 1
    \$\begingroup\$ (1+!x)#'"*" -> ,\x#"*" \$\endgroup\$ – ngn Jan 13 '18 at 22:12
2
\$\begingroup\$

Japt -R, 8 4 bytes

õ_î*

Try it online!

4-byte alternative:

°Tî*

Try it online

\$\endgroup\$
  • 1
    \$\begingroup\$ You know, instead of adding a newline to every line, joining with spaces and trimming, you could just join with newlines ;-) \$\endgroup\$ – ETHproductions Feb 27 '17 at 14:56
  • \$\begingroup\$ Could you use this 5 byte version? \$\endgroup\$ – Shaggy Jun 19 '17 at 12:18
1
\$\begingroup\$

Gema, 36 characters

*=@repeat{*;@append{s;\*}@out{$s\n}}

Sample run:

bash-4.3$ gema '*=@repeat{*;@append{s;\*}@out{$s\n}}' <<< 5
*
**
***
****
*****
\$\endgroup\$
1
\$\begingroup\$

Forth, 39 bytes

Quite simple, with a couple of nested loops. ASCII 42 is an asterisk.

: f 0 do I -1 do 42 emit loop CR loop ;

Try it online

Prints a trailing newline.

\$\endgroup\$
1
\$\begingroup\$

Bash, 35 characters

for((;i++<$1;));{ s+=\*;echo "$s";}

Sample run:

bash-4.3$ bash draw-an-asterisk-triangle.sh 5
*
**
***
****
*****
\$\endgroup\$
1
\$\begingroup\$

C++, 108 chars

#import<iostream>
main(){int n;std::cin>>n;for(int i=1;i<=n;++i){for(int j=i;j--;)std::cout<<"*";puts("");}}

Straightforward.

Try it online

\$\endgroup\$
  • \$\begingroup\$ Can the < be moved directly next to the #include? (I don't do C++, just a wild guess based on Java knowledge) \$\endgroup\$ – Addison Crump Oct 10 '16 at 14:30
  • \$\begingroup\$ You're right.__ \$\endgroup\$ – John Doe Oct 10 '16 at 14:31
  • 1
    \$\begingroup\$ The #include does need to be included in the byte count. \$\endgroup\$ – mbomb007 Oct 10 '16 at 14:39
  • \$\begingroup\$ Thanks for the C++ solution, but there's a shorter one ;-) \$\endgroup\$ – Sickboy Oct 11 '16 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.