83
\$\begingroup\$

Background

This is a standard textbook example to demonstrate for loops.

This is one of the first programs I learnt when I started learning programming ~10 years ago.

Task

You are to print this exact text:

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

Specs

  • You may have extra trailing newlines.
  • You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines.

Scoring

This is . Shortest answer in bytes wins.

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 88653; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();
    
    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
  • 2
    \$\begingroup\$ @DylanMeeus "You are to print this exact text:" \$\endgroup\$ – Leaky Nun Aug 4 '16 at 12:56
  • 13
    \$\begingroup\$ @DylanMeeus Since that is to do with the dev tools hiding repeated console outputs, and isn't native to JavaScript consoles as a whole and is not in the JavaScript spec - as well as the fact that feature can be turned off - i think it should be acceptable. Not all browsers will collapse it like that. \$\endgroup\$ – Trotski94 Aug 4 '16 at 12:58
  • 6
    \$\begingroup\$ @LeakyNun Leaderboard snippet please! \$\endgroup\$ – dkudriavtsev Aug 4 '16 at 22:08
  • 2
    \$\begingroup\$ One of the most interesting things about this challange is that depending on your language ********** can be shorter then a loop. Makes me wonder when it's better for a given language to switch between 1 or 2 loops. \$\endgroup\$ – dwana Aug 5 '16 at 9:14
  • 1
    \$\begingroup\$ you say trailing new lines are acceptable. Are leading newlines acceptable too? \$\endgroup\$ – Albert Renshaw Feb 10 '17 at 2:34

270 Answers 270

1
\$\begingroup\$

Io, 32 bytes

10repeat("*"repeated(10)println)

Try it online!

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

Julia, 23 bytes

print(("*"^10*"\n")^10)

Explanation:

print(                ) # Print
      (           )     # A string consisting of 
       "*"^10           # "*" duplicated 10 times
             *"\n"      # then concatenated to a newline
                   ^10  # which is then duplicated 10 times
\$\endgroup\$
1
\$\begingroup\$

Canvas, 5 bytes

*A×A*

Try it online!

With notes (not valid code, as Canvas does not support comments):

          Print the following (implicit)
*         The string "*"
 A×      Duplicated 10 times horizontally
    A*  Duplicated 10 times vertically
\$\endgroup\$
1
\$\begingroup\$

Japt -R, 5 bytes

AÆAç*

Try it online!

Unpacked & How it works

Ao@Aç*

Ao@    Map range(10) with a function that returns...
Aç*      "*" repeated 10 times.
       `-R` flag joins the result array with "\n"
       Implicit output
\$\endgroup\$
1
\$\begingroup\$

Japt -R, 5 bytes

AÆAî*

Test it

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

Tcl, 25 bytes

time {puts **********} 10

Try it online!

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

Python 2, 20 bytes

print("*"*10+"\n")*10

I didn't know you could remove the space between print and the string.

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

Q'Nial7, 15 bytes

10 10reshape'*'               #create atom '*', reshape to 10 by 10 matrix
\$\endgroup\$
1
\$\begingroup\$

Z80Golf, 14 bytes

00000000: 0a4f 3e2a 46ff 10fd 7eff 0d20 f576       .O>*F...~.. .v

Try it online!

Disassembly

start:
  ld a, (bc)  ; 0a
  ld c, a     ; 4f
loop1:
  ld a, '*'   ; 3e 2a
  ld b, (hl)  ; 46
loop2:
  rst $38     ; ff
  djnz loop2  ; 10 fd
  ld a, (hl)  ; 7e
  rst $38     ; ff
  dec c       ; 0d
  jr nz, loop1  ; 20 f5
  halt        ; 76

Golfing nested loops

Since a is the parameter to putchar, I used b and c for loop counters. The loop constructs are

  ld b, ... ; 1 or 2 bytes
loop:
  (loop content)
  djnz loop ; 2 bytes

and

  ld c, ... ; 1 or 2 bytes
loop:
  (loop content)
  dec c     ; 1 bytes
  jr nz, loop ; 2 bytes

This combination of 2-level nested loops is optimal in Z80Golf.

Reusing the first instruction as data

The first byte 0a is located at memory address $0000. Since hl is always zero in this program, we can use the one-byte instruction ld r, (hl) whenever we need the constant 0a, instead of the two-byte ld r, $0a.

In this particular challenge, the byte $0a has three uses: the outer loop, the inner loop, and the newline character. The byte as an instruction is not particularly useful, so we save two bytes here.

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

Matlab, 17 bytes

@()repmat('*',10)

Try it Online

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

Shakespeare Programming Language, 387 bytes

,.Ajax,.Ford,.Act I:.Scene I:.[Exeunt][Enter Ajax and Ford]Ford:You be twice the sum ofa cat twice twice the sum ofa cat a big big cat.Speak thy.Speak thy.Speak thy.Speak thy.Speak thy.Speak thy.Speak thy.Speak thy.Speak thy.Speak thy.You be twice the sum ofa cat a big big cat.Speak thy.Ajax:You be the sum ofyou a cat.Be you nicer the sum ofa cat a big big big cat?If notlet usScene I.

Try it online!

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

q, 12 bytes

10 10#get"*" / a 10x10 matrix
\$\endgroup\$
  • \$\begingroup\$ 10 10#(*) should have the same effect. But I'm not sure if spaces are allowed between asterisks. \$\endgroup\$ – ngn Sep 28 '18 at 1:24
1
\$\begingroup\$

MBASIC, 32 bytes

1 WIDTH 10:PRINT STRING$(100,42)

RUN
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********

No loop. Just printing 100 asterisks into a 10 character wide terminal to force line wraps.

There's no MBASIC on TIO, so I've linked the reference manual.

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

R 33 bytes

cat(rep('**********',10),sep='
')

Try it online

I believe this is shorter than the other R answers on this question.

\$\endgroup\$
  • \$\begingroup\$ I believe this is shorter than yours, but Mamie's answer on the first page (sorted by oldest) is something like 26 bytes if the comments are to be believed. \$\endgroup\$ – Giuseppe Feb 19 at 22:14
  • \$\begingroup\$ Ah, I'd missed that one, thanks @Giuseppe. \$\endgroup\$ – CT Hall Feb 19 at 22:31
1
\$\begingroup\$

C# (.NET Core), 53 bytes

Brand new to code golf, is this type of format allowed to be used (Usage of the header section / footer section)?

for(int i=0;i<10;i++){Console.Write("**********\n");}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG, and Great First Answer \$\endgroup\$ – Taylor Scott Feb 19 at 22:46
  • \$\begingroup\$ You can get it down to 49 bytes by moving the i++ into the conditional expression, and moving the block body into the increment statement: for(int i=0;i++<10;Console.Write("**********\n")); (try it online) \$\endgroup\$ – mgthomas99 Feb 20 at 14:47
  • 1
    \$\begingroup\$ This is not valid since it's neither a function (lambdas count) nor is it a full program. With a few adjustments though, 42 \$\endgroup\$ – ASCII-only Feb 20 at 16:29
  • \$\begingroup\$ @mgthomas99 btw that's 50 bytes, and it makes no difference whether the write is inside or outside \$\endgroup\$ – ASCII-only Feb 20 at 16:30
1
\$\begingroup\$

CSS only, 157 109 bytes

Inspired by hd answer, probably 1:1 reproduced from OP question (except background color)

body:after,body:before{white-space:pre;content:'**********\A**********\A**********\A**********\A**********\A'

\$\endgroup\$
  • 1
    \$\begingroup\$ 103 bytes: *,:after{margin:0;white-space:pre;content:'**********\A**********\A**********\A**********\A**********\A (FireFox only, save it inside <style>...</style> in a totally empty file), the :after matches every element's after (in this case html and body) and * is used to remove the body margin. \$\endgroup\$ – Night2 Oct 15 at 5:43
1
\$\begingroup\$

Perl 5, 18 Bytes

say'*'x10for 1..10

Requires the -E flags, as in:

perl -E "say'*'x10for 1..10"
\$\endgroup\$
1
\$\begingroup\$

Forth (gforth), 36 34 bytes

: f 9 for ." **********" cr next ;

Try it online!

-2 bytes thanks to @bubbler

Explanation

 10 0            \ put 10 and 0 on the stack
 do              \ begin a loop from 0 to 10 (0 inclusive 10 exclusive)
 ." **********"  \ print the string literal ********** (the initial space is required because forth words are space separated, and ." is not an exception)
 cr              \ print out a new line character
 loop            \ end the loop
\$\endgroup\$
  • \$\begingroup\$ Using for..next loop is 2 bytes shorter: Try it online! \$\endgroup\$ – Bubbler Oct 12 at 8:13
1
\$\begingroup\$

PHP, 26 bytes

Just used a compressed string. Has raw output of gzdeflate and contains unprintable binary data, so the code itself and direct TIO link cannot be posted here, but here is a hex dump of it:

000000  3c 3f 3d 67 7a 69 6e 66 6c 61 74 65 28 22 d3 d2  <?=gzinflate("..
000010  82 01 2e 2d 9a 33 01 22 29 3b                    ...-.3.");

Save it as a binary file then execute it like this: php asterisks.php

TIO which uses bash to run this file: Try it online!

\$\endgroup\$
0
\$\begingroup\$

C++, 76 bytes

I don't know if this could be golfed further, but just.

#include <iostream>
void a(){for(int i=0;i++<10;)std::cout<<"**********\n";}
\$\endgroup\$
  • \$\begingroup\$ No, I tried that. \$\endgroup\$ – user54200 Aug 4 '16 at 10:30
  • 3
    \$\begingroup\$ You can save a few bytes by using puts from cstdio instead of cout (save in header name, function name, plus line terminator for free). Also one byte by making i global (which gets zero initialized for free). \$\endgroup\$ – Mat Aug 4 '16 at 12:23
  • \$\begingroup\$ This isn't a whole program (no main) so do you need the include? \$\endgroup\$ – Jerry Jeremiah Jul 2 '18 at 0:07
0
\$\begingroup\$

C# - 88 bytes

class P{static void Main(){int i=0;while(i++<10)System.Console.Write("**********\n");}}
\$\endgroup\$
  • \$\begingroup\$ You can reduce this a bit by using a for look, putting int i inside it for(int i=10;i-->0;) (There is never a reason to use a straight while loop in C# code golf, a for loop is never more expensive) \$\endgroup\$ – VisualMelon Aug 4 '16 at 17:24
  • \$\begingroup\$ I know, but then I would have been copying and pasting an already existing answer. \$\endgroup\$ – pay Aug 4 '16 at 17:28
0
\$\begingroup\$

Perl, 24 bytes

print((("*"x10).$/)x10);

\$\endgroup\$
0
\$\begingroup\$

Javascript (using external library - Enumerable) (41 bytes)

_.From("**********\n").Cycle(120).Write()

Link to lib: https://github.com/mvegh1/Enumerable/

Code explanation: This runs right in the console. Load the string into the library, which parses it to a char array enumerable. Create a new enumerable from that sequence, which is generated by cycling from start to finish 120 times (because the string length is 12, and we want 10 of them..12*10=120). I.e [1,2,3].Cycle(10) would be 1,2,3,1,2,3,1,2,3,1. Finally, join everything into a string with "" as delimiter

enter image description here

\$\endgroup\$
  • \$\begingroup\$ OH, .length lied to me ahah...I thought it would count "\" and "n" as separate characters..fixed! \$\endgroup\$ – applejacks01 Aug 4 '16 at 17:58
  • \$\begingroup\$ Next time use mothereff.in/byte-counter \$\endgroup\$ – Patrick Roberts Aug 5 '16 at 0:01
  • \$\begingroup\$ @PatrickRoberts Got it, thanks! \$\endgroup\$ – applejacks01 Aug 5 '16 at 0:07
0
\$\begingroup\$

Ruby, 18 bytes

puts (?**10+$/)*10

Alternative version (+3 bytes)

10.times {puts ?**10}

Ungolfed (first version)

puts ('*' * 10 + '\n') * 10
\$\endgroup\$
0
\$\begingroup\$

Swift 2, 45 Bytes

func a(){for _ in 0...9{print("**********")}}
\$\endgroup\$
0
\$\begingroup\$

Wolfram, 22 bytes

Grid[Table["*",10,10]]
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! I can't test right now, but I don't think this is a full program (it only displays correctly when used in Mathematica's notebook front end, which constitutes a snippet by this community's standards). If you put this in a source file and call it with wolfram -script file.m I don't think it'll print anything. I think the shortest way to get around that would be Print@@@Table["*",10,10]. Still, nice solution! :) \$\endgroup\$ – Martin Ender Aug 4 '16 at 20:11
  • \$\begingroup\$ You are correct. Also, your solution works and is 24 bytes long. \$\endgroup\$ – Travelling Particle Aug 4 '16 at 20:29
0
\$\begingroup\$

R

matrix(rep("*",100), nrow = 10)

Probably faster way in R, but fun utilization of matrix

Explanation

rep: repeats first argument as many times as second argument.

matrix: creates matrix from vector (first argument), and nrow is the number rows desired in matrix.

\$\endgroup\$
  • 1
    \$\begingroup\$ Hi, and welcome to PPCG! However, we require all code to be golfed, which this isn't. Please golf it. \$\endgroup\$ – Rɪᴋᴇʀ Aug 5 '16 at 0:07
  • 1
    \$\begingroup\$ To make it print the actual desired output you would need to loop cat over it, one way or another. In addition, because of vector recycling, matrix("*",nr=10,nc=10) or array("*",c(10,10)) would be more concise to get the same matrix as the one you generate. \$\endgroup\$ – plannapus Aug 5 '16 at 7:12
  • \$\begingroup\$ You are right in all regards. This works :for(i in 1:10){for (j in 1:10){cat("*");if(j == 10){cat("\n")}}} \$\endgroup\$ – cgage1 Aug 5 '16 at 16:54
0
\$\begingroup\$

JAISBaL 3.0.1, 9 bytes (non-competing)

h**A10«

Verbose:

# \# enable verbose parsing #\
ten            \# [0] push ten onto the stack #\
push1 *        \# [1] push * onto the stack #\
mul            \# [2] multiply the top two values of the stack #\
dupmany 10     \# [3] duplicate the top value of the stack 10 times #\
popoutallln    \# [4] pop off every value in the stack and print each one with a new line #\

Conventional 10 byte version (using actual for loops):

˖˖S*˄P

Verbose:

# \# enable verbose parsing #\
ten                 \# [0] push ten onto the stack #\
for                 \# [1] start for loop #\
    ten             \# [2] push ten onto the stack #\
    for             \# [3] start for loop #\
        print1 *    \# [4] print * #\
    end             \# [5] end current language construct #\
    ln              \# [6] print a new line #\

This is non-competing because JAISBaL has received a huge amount of updates yesterday and today, and I'm not sure whether or not these instructions were available or did the same thing, furthermore, all the instructions ids have changed...


intepreter

\$\endgroup\$
0
\$\begingroup\$

Javascript, 45 bytes

for(i=0;i<10;i++) {console.log('**********')}

even better, ES6 Javascript, 38 bytes

console.log('**********\n'.repeat(10))

open console and copy paste to test

\$\endgroup\$
0
\$\begingroup\$

Python 3 (22 bytes)

print(('*'*10+'\n')*10)
\$\endgroup\$
  • \$\begingroup\$ 23 bytes - I believe '\n' is two bytes of code, but if you measured with len it will have said 22. \$\endgroup\$ – Jonathan Allan Aug 7 '16 at 6:16

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.