Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Inspired by some of the other answers to this SO question http://stackoverflow.com/questions/11567823/print-a-line-10-times-in-obj-c/11568151#11568151 your task is to print "Print this line" 10 times in the most creative way possible using your favourite language.

An example (and not very creative) implementation in C is:

#include<stdio.h> 
main()
{
    for(int i = 0; i < 10; i++)
        printf("Print this line\n");
}

Points will be awarded for creativity, and for (ab)using language features such as object orientation, threading, LINQs, pointers etc.

This is not a code golf, so feel free to go overboard, and have fun!

share|improve this question
12  
There is not "objective winning criteria" here as demanded by the FAQ. – dmckee Jul 23 '12 at 15:54
4  
Oh, so this is why I've been getting mysterious upvotes on my terrible answer. Guess I'll have to try to make it even more outrageous. – Josh Caswell Jul 23 '12 at 20:06
1  
@milo5b See dmckee's comment above. – Gareth Jul 24 '12 at 9:25
1  
@Gareth I have read that, but I only partially agree. Although it is true the points are not given on objective criteria, the points' count itself it's definitely objective. – milo5b Jul 24 '12 at 9:28
2  
I would like to say that points count is the objective, but I've seen people get flamed for using points as a metric. Does anyone have any better suggestions? – Hannesh Jul 24 '12 at 21:54
show 3 more comments

closed as off topic by Mr.Wizard, Chris Jester-Young Jul 30 '12 at 17:13

Questions on Programming Puzzles & Code Golf Stack Exchange are expected to relate to programming puzzle or code golf within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

53 Answers

1 2

LOLPython

I CAN HAZ CHEEZBURGER
WHILE I CUTE?
    IZ ALLFINGERZ BIG LIKE I?
        COMPLAIN "Print this line"
        I GETZ ANOTHR CHEEZBURGER
    NOPE?
        KTHXBYE
share|improve this answer
Does that actually work? That's awesome if it does. – navnav Jul 28 '12 at 7:05
1  
There goes my weekend, now I'll read about LOLPython. <accusing> Thank you so much </accusing> – Tobias Kienzler Jul 28 '12 at 7:28
1  
Yeah it does work (just gets translated to python). And I hope you enjoy your weekend Tobias :P – grc Jul 28 '12 at 9:04
4  
I'm not convinced that this is the most creative way to do this in LOLPython. The question even gives an example non-creative answer that is almost identical to this answer, just in C. – Matt Jul 29 '12 at 1:47

JavaScript + jQuery

Mandatory steps:

  1. Go to http://api.codegolf.stackexchange.com/ (due to security policies.)
  2. jQuerify it.

Run this code in your preferred JS console:

$.getJSON('http://api.codegolf.stackexchange.com/1.1/revisions/6707', function(json) {
    c_code = (/{\n    ([\s\S]*)\n}/.exec(json['revisions'][0]['body']))[1];
    eval(c_code.replace(/printf/, "console.log").replace(/&lt;/, "<").replace(/int/,""));
});

Yep, it's reading the C sample implementation through this question in StackExchange's API and doing some replaces to make it work using... JS's eval (as if it wasn't bad enough :P)

share|improve this answer
3  
I'm surprised this one doesn't have more upvotes.. – Izkata Jul 24 '12 at 2:42
3  
I can't decide whether this is horrible or awesome. +1 anyway. – Polynomial Jul 24 '12 at 11:17

Python

import sys
sys.setrecursionlimit(11)
def Print_this_line():
    Print_this_line()

Print_this_line()

From the REPL

>>> import sys
>>> sys.setrecursionlimit(11)
>>> def Print_this_line():
...     Print_this_line()
... 
>>> Print_this_line()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in Print_this_line
  File "<stdin>", line 2, in Print_this_line
  File "<stdin>", line 2, in Print_this_line
  File "<stdin>", line 2, in Print_this_line
  File "<stdin>", line 2, in Print_this_line
  File "<stdin>", line 2, in Print_this_line
  File "<stdin>", line 2, in Print_this_line
  File "<stdin>", line 2, in Print_this_line
  File "<stdin>", line 2, in Print_this_line
  File "<stdin>", line 2, in Print_this_line
RuntimeError: maximum recursion depth exceeded
share|improve this answer
Thought about this too, but didn't know about sys.setrecursionlimit :O I faked it using an extra arg and didn't quite like it. – kaoD Jul 23 '12 at 22:56
8  
@kaoD, who says this site isn't useful for learning :) – gnibbler Jul 23 '12 at 23:09
2  
hehe, ... it doesn't print though, just calls itself ! – wim Jul 24 '12 at 4:16
it has the same line printed 10 times on the terminal, so it qualifies as a great valid answer. – Evgeny Jul 30 '12 at 12:56

JavaScript

var lim = document.getElementById("answer-6723").getElementsByClassName("vote-count-post")[0].innerText-0;
for(var z = 0; z<lim; z++) {
    if(z > 9) {
        continue;
    }
    console.log("print this line");
}

Run in the console while on this page. It reads the number of votes this answer has and prints that many lines. So I'll be requiring 10 up-votes... :P

share|improve this answer
10  
+1 (but no upvote of course). – ugoren Jul 24 '12 at 7:13
6  
I'm tempted to upvote and break it... ;-) – Gareth Jul 24 '12 at 10:13
1  
@DisgruntledGoat If you make an edit to the original fast enough, no edit is shown in the history. – Gaffi Jul 24 '12 at 13:36
1  
@Gaffi, you ruined my secret! – Griffin Jul 24 '12 at 13:37
1  
@Griffin "Oh gosh, how silly of me" I see what you did there ;) – kaoD Jul 24 '12 at 15:07
show 4 more comments

C, Recursive main

It's actually a pretty useful CodeGolf technique.
I also rely on the fact that ac is initially 1 (with no command line arguments).

int main(int ac, int av) {
        return ac++<11?main(ac,printf("Print this line\n")):0;
}
share|improve this answer
Is that even legal? I thought main isn't allowed to be called explicitly. – Mechanical snail Aug 1 '12 at 18:40
@Mechanicalsnail, main is just a function. The runtime calls it, but nothing prevents you from calling it too. – ugoren Aug 2 '12 at 7:21

C++ (template meta-programming)

#include <iostream>
#include <string>

template <int N> struct print
{
    static inline void line(const std::string &s)
    {
        std::cout << s << std::endl;
        print<N-1>::line(s);
    }
};

template <> struct print<0>
{
    static inline void line(const std::string &s)
    {
    }
};

int main()
{
    print<10>::line(std::string("Print this line"));
    return 0;
}
share|improve this answer

Javascript

deletefunc=function(event)
{
    document.body.removeChild(event.target.parentNode);
    addfunc();
}

addfunc=function()
{
    var p=document.createElement('p');
    p.style.position='fixed';
    p.style.top=Math.random()*700+'px';
    p.style.left=Math.random()*1000+'px';
    p.appendChild(document.createTextNode("Print this line"));
    closebutton=document.createElement('button');
    closebutton.appendChild(document.createTextNode("X"));
    closebutton.addEventListener('click',deletefunc);
    p.appendChild(closebutton);
    document.body.appendChild(p);
}

for(loop=0;loop<10;loop++)
{
    addfunc();
}

To run, just copy and paste the code into the JavaScript console of your browser.

Creates ten randomly positioned p nodes with a close button. Replaces each closed paragraph with another one.

Entirely pointless, but a fun distraction nonetheless.

share|improve this answer
Cool idea! Unfortunately, nodes are created in the bottom left of all sites I tried. Using Chrome, in case it helps. – kaoD Jul 23 '12 at 16:05
@kaoD Yeah, I've just edited to say that you should use an 'about:blank' page to get correct results. I'll have to see if I can modify it so that it works on any page. – Gareth Jul 23 '12 at 16:07
Great, it's working fine there :) – kaoD Jul 23 '12 at 16:09
@Gareth I have accidentally downvoted your post, could you please make a small edit so I can take off the downvote you do not deserve? Thanks and sorry :) – milo5b Jul 26 '12 at 15:44
@milo5b Ah, I wondered what the downvote was for. :-) – Gareth Jul 26 '12 at 15:46

Python

for x in 1,2,3,4: print "Print this line\n"*x
share|improve this answer
It could be cooler (or not, depends of your taste) to replace 1,2,3,4 by range(5). It adds the 0, but printing 0 times is ok! – Oltarus Apr 23 at 14:55

Excel

Copy this formula into every cell in column A.

=IF(ROW()<=10,"Print this line","")
share|improve this answer

self modifying x86 assembly

.data # here be dragons

str:    .ascii "Print this line\0"

        .globl main
main:
        mov $10,%eax
        test %eax,%eax
        jz .Lend
        push $str
        call puts
        decb (1+main)
        jmp main
.Lend:  call exit

This works under Linux. Use cc -m32 -o ten ten.s to assemble.

Here is a x86-64 edition for all those guys with a modern processor:

       .data # here be dragons

0:     .ascii "Print this line\0"

       .globl main

main:   mov $10,%eax
        test %eax,%eax
        jz 1f
        mov $0b,%rdi
        call puts
        decb (1+main)
        jmp main
1:      ret
share|improve this answer

BrainFu Unfortunately, printing of the line feed character ASCII 10 may be implementation dependent.

++++[>+++++<-]>[>++++>++++>++++>++++>++++>++++>++++>++++>++++<<<<<<<<<-]+++++[>++++>++++>++++>++++>++++>++++>++++>++++<<<<<<<<-]>+>++++>+++++>++++++++<<<<+++++[>>>>>++>++>++>++<<<<<<<<-]>>>>>>++++>+++++>++++++><<<<<<<<<<++++[>++++++++<-]<++++++++++<++++++++++[>>>>>>>>>>>>.<<<.<<<.>>.>>>.<<<<<<<<.>>>>>>>>.<<<<<<.>.>>>>.<<<<<<<.>>>>.<.>>.<<<<.<<.<<-]
share|improve this answer
   print "Print this line 10 times"
   print "send this to all your friend or a code monkey will come and eat your hard disk"
share|improve this answer

Mathematica

When the processor reads the output of line 1, it realizes that it needs to obey the command it sees. This causes it to issue line 2. And so on. It gives up after the tenth line.

g[{x__}]:=(r=Hue[RandomReal[]];{Style["Print[",r],x,Style["]",r]})
Row[#]&/@NestList[g, {"Print[this line]"},10]//TableForm
FromCharacterCode[{84,104,105,115,32,105,115,32,101,120,97,115,112,101,114,97,116,105,110,103,46,32,73,32,103,105,118,101,32,117,112,33}]

output

share|improve this answer

Python 2.7

from __future__ import print_function
import itertools
import random
import string

random.seed(440)
count = int(''.join([random.choice(string.digits) for x in range(2)]))
map(print,itertools.repeat('Print this line',count))
share|improve this answer

PHP

<?
$line = "Print this line";
$ops = array(
  'echo' => array('t' => false, 'p' => false, 'a' => false),
  'print' => array('t' => false, 'p' => true, 'a' => false),
  'printf' => array('t' => false, 'p' => true, 'a' => true),
  'echo sprintf' => array('t' => false, 'p' => true, 'a' => true),
  '<?=' => array('t' => true, 'p' => false, 'a' => false),
);
foreach ($ops as $c => $t)
{
    for($i=0;$i<2;$i++)
    {
      eval(($t['t'] ? '?>' : '') . $c . ($t['p'] ? '(' : '') . ($t['a'] ? '"%s",' .'"' . $line . "\n" : '"' . $line . "\n") . '"' . ($t['p'] ? ')' : '') . ';' . ($t['t'] ? '?>' : ''));
    }
}
share|improve this answer

Ruby 1.9

Not sure why this happened. Some boring stuff first:

class Tadpole
  attr_reader :v, :t
  def initialize; @v,@t = 0,[] end
  def to_s; [v,*t].map { |c| c.chr }*'' end
  def -@; @v += 10; self end
  def ~; @v += 1; self end  
  def / o; @t << o.v; self; end
end

def o; Tadpole.new; end
def tadpoles! x,y; puts [x.to_s]*y.v end

I call it "tadpoles at the starting line"

tadpoles!            --------o /
             ~~~~-----------o /
            ~~~~~----------o /
               -----------o /
        ~~~~~~-----------o /
                   ~~---o /
      ~~~~~~-----------o /
        ~~~~----------o /
      ~~~~~----------o /
    ~~~~~-----------o /
              ~~---o /
~~~~~~~~----------o /
  ~~~~~----------o /
     -----------o /
    ~----------o ,
             -o
share|improve this answer

Python 2.6

2.7 doesn't work. Don't ask.

#!/usr/bin/env python
import sys
class _main_:
    def __call__(*_):
        i = 0
        if 1 < len(_) <= 3:
            return _[-1].__class__.__name__
        elif len(_) > 4:
            return _[-1].__class__
        while all(n < 16 for n in (i, len(_[0](_[0])))):
            c = '\tcKZr~sGKj~RKZ<!'[i]
            try:(
                (_[0] + sys.copyright)
                (sum((_[0], getattr(__builtins__, dir(__builtins__)[ord(c) + 21]).__name__[0])))
            )
            except Exception as e:
                if _[-1] == 'I'.find(_[0](c, e)[0]):
                    pass
                else:
                    _[0](e, i, sys, _[0]).__name__ += '\n'
                    i = -1
            i += 1
    def __add__(*_):
        return sys.stdout.write
    def __radd__(*_):
        return _[0](_[0])[sys.maxint:]
    def __cmp__(*_):
        return (((_[-2] + 1)(' ' if not _[-1] else '\n'), _[-1])[1])

_main_()()
share|improve this answer

Ruby

srand 10
puts 'Print this line' while rand(100) != 36
share|improve this answer
ideone.com/b5IJg – Griffin Jul 24 '12 at 14:16
I don't know why. Random algorithm should be the same. – Łukasz Niemier Jul 24 '12 at 16:57

C++

I don't like having the string in the source code. Let's try some security by obscurity (TM) and wasting CPU cycles.

The code does the following:

  • Generate a base string Peiet teie eiee\n

The string contains some of the final characters (P,i,t,the last e,\n), but has a nice fractal-like structure so we can use a function that generates aba from two strings a and b (sorry for the minor memory leaks)

  • Compute the 9928509th prime number - let's call it P

We could use the number (it's 178066393) directly, but we honor our mighty CPU this way.

  • Repeat the next step P times
  • There are 7 e in the base string, increment them and set them back to e if they reach 'e' + x[n] with x[] containing the 7 primes from 17 to 37

Again, we could generate the result in an instant with some basic math, but prefer a loop with millions of iterations. Additionally, we reuse the prime table we generated before.

  • Print the resulting string 10 times

Code:

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <math.h>

#define L 17
#define V 16384

unsigned char s[L], t[L], si = 0;
int i, j, p, q, v[V];

bool isPrime(int p) {
  int n;
  if ((p % 2) == 0) return false;
  for (n = 2; v[n] <= sqrt(float(p)); n++) {
    if ((p % v[n]) == 0) return false;
  }
  return true;
}

void FindNextPrime(int& p) {
  do {p+=2;} while (!isPrime(p));
}

char* d(char* a, char* b) {
  char* u = (char*)malloc(L);
  sprintf(u,"%s%s%s",a,b,a);
  return u;
}

void c(char* cc) {
  do {
    t[si] = *cc;
    s[si++] = *cc;
  } while (*(++cc));
}

int main() {
  // Generate base string
  c("P");
  c(d("e","i"));
  c(d("t"," "));
  c(d(d("e","i")," "));
  c("e\n");
  s[L] = t[L] = 0;
  // Compute prime number
  i = 2; p = 3;
  do {
    if (i < V) v[i] = p;
    FindNextPrime(p);
  } while (++i != 9928509);
  // Generate final string
  i = 0;
  do {
    q = 7;
    for (j = 0; j < L-3; j++) {
      if (s[j] == 'e') {
        if (t[j]++ >= ('e' + v[q])) t[j] -= v[q];
        q++;
      }
    }
  } while (i++ != p);
  // Output string
  for (i = 0; i < t[L-2]; i++) {
    printf("%s",t);
  }
  return 0;
}
share|improve this answer

C

// algo is  |
// here     V
#define    start                           main(n){
#define    print                           printf(
#define    this                            "this __________\n"    
#define    line                            );
#define    and                             ;
#define    recurse                         main(++n);}
#define    less_than_equal_to_10_times     (n<=10)
#define    then                            {
#define    end                             }
//          ^
//          |


start
        if less_than_equal_to_10_times then print this line and recurse
end

share|improve this answer

Curl & grep

    curl -s http://codegolf.stackexchange.com/questions/6707/print-a-line-10-times-in-the-most-creative-way-possible | /bin/grep -o -m 10 'Print this line'
share|improve this answer

TSQL

;with RecursiveCTE as (
  select 1 as id
  union all
  select id + 1 
  from RecursiveCTE
)
select top 10 
    'Print this line'
from RecursiveCTE;

Nothing a recursive CTE can't solve... [Demo]

Of course, there's the simpler alternative:

print 'Print this line'
go 10

but this has no value in the current context.

share|improve this answer

Neato

Neato is a Unix graph layout utility.

graph {
  n0[color=white,label="Print this line"];
  n1[color=white,label="Print this line"];
  n2[color=white,label="Print this line"];
  n3[color=white,label="Print this line"];
  n4[color=white,label="Print this line"];
  n5[color=white,label="Print this line"];
  n6[color=white,label="Print this line"];
  n7[color=white,label="Print this line"];
  n8[color=white,label="Print this line"];
  n9[color=white,label="Print this line"];
}

Compile it like:

neato -Tpng g.dot > g.png

Which gives you:

enter image description here

share|improve this answer

Bash

#!/bin/bash
export i=$((i+1))
if [ $i -le 10 ]; then
  echo Print this line
  $0
fi
share|improve this answer

JavaScript

Tee hee.

var whee = {
    get whee(whee) {
        for(;;) {
            if(ee.l = !ee.l) break;

            return 3;
        }

        whee = arguments;
        whee = whee.callee;
        whee.whee = whee.caller.whee + 1 | 0;

        if(whee.whee / ee.whee <3) {
            whee();
        }

        ee.ee = 'Print this line';
        o.O
    },
    set ee(vee) {
        ee.vee = vee;
    },
    get ee(vee) {
        return {
            get O() { o.o[beegee](ee.vee + '<br>'); },
            get o() { return document; }
        };
    }
}, ee = whee, o = whee.ee, beegee = /\w(?:r)*i?($||t)(?!e)/g;
beegee = (beegee + beegee).match(beegee).slice(0, 5).join('');

whee.whee

Run in your console, or just go have a look-see.

share|improve this answer
1  
Error: Getter functions must have no arguments (FF 13) – Izkata Jul 24 '12 at 2:43
@Izkata: Don't use Firefox 13 then :P It is guaranteed to work only on Chromium. (You can also take out the arguments to all getters and make sure to declare whee in whee.whee.) – minitech Jul 24 '12 at 2:43

C#

This task requires enterpriseification. Here you go (uses a factory to create a generic class that uses a factory to create a generic class that .... uses the factory to create a class that prints the lines):

void Main()
{
   ILinePrinter lp = LinePrinterFactory.CreateLinePrinter(9);
   lp.PrintTheLine();
}

public static class LinePrinterFactory
{
   public static ILinePrinter CreateLinePrinter(int level)
   {
      if (level==0)
        return new LinePrinter();

      Type insideType = CreateLinePrinter(level - 1).GetType();
      Type tg = typeof(LinePrinter<>);
      return (ILinePrinter) Activator.CreateInstance(tg.MakeGenericType(insideType));
   }
}

public interface ILinePrinter
{
  void PrintTheLine();
}

public class LinePrinter: ILinePrinter
{
  public void PrintTheLine()
  {
     Console.WriteLine("Print this line");
  }
}

public class LinePrinter<T>:ILinePrinter where T:ILinePrinter, new()
{
   public void PrintTheLine()
   {
      ILinePrinter lp = new LinePrinter();
      lp.PrintTheLine();
      lp = new T();
      lp.PrintTheLine();
   }
}
share|improve this answer

scala

print("Print this line\n"*10)

or

case class Times(cnt:Int) {
  def times(msg:String) = print(msg*cnt)
}
implicit def toTimes(cnt:Int) = Times(cnt)

10 times """Print this line
"""
share|improve this answer

K

do[10;{$[#x;$[x[0]~a:(*1?.Q.a,.Q.A," ");[1 a;if[.z.o like "l*";.,["\\"]"sleep 0.1"];.z.s 1_x];.z.s x];[-1"";]]}"Print this line"]

Picks a random char and if it matches the first letter in the string, it prints it to stdout, then recursively cycles through the string, repeating the same.

share|improve this answer
I like random solutions. – woliveirajr Jul 25 '12 at 12:31

C#

Recursively call a method that recursively splits the string until we're down to a single character, then prints that. For fun, flip the Cut() calls and the line prints backwards.

    using System;

namespace PrintThisLine
{
    class Program
    {
        static void Main(string[] args) {
            string theLine = "Print this line";
            int counter = 10;

            Stutter( 10, theLine );

        }

        private static void Stutter(int repeat, string theLine)
        {
            if (repeat <= 0) return;
            else
            {
                Cut(theLine  );
                Console.WriteLine("\t" +  repeat );
                repeat--;
                Stutter(repeat,theLine  );
            }
        }

        static void Cut (string whatsLeft) {
            if (whatsLeft.Length < 2) Console.Write( whatsLeft );
            else
            {
                Cut( whatsLeft.Substring( 0, whatsLeft.Length / 2 ));
                Cut( whatsLeft.Substring( whatsLeft.Length / 2, (whatsLeft.Length - whatsLeft.Length / 2) ) );
            }

        }

    }
}
share|improve this answer

MATLAB/Octave

repmat(char("qsjou!uijt!mjof"-1), 10, 1)
share|improve this answer
1 2

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