Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Your task is to reverse the order in which some prints get executed.

Your code will be in this form:

//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code

You will have to print (or echo, or write, or equivalent) those strings from the fourth to the first.

  • You decide which lines of your program must print the strings, but they must be adjacent;

  • Every line can contain only one print, and cannot exceed 60 bytes in length;

  • Since this is , be creative and avoid to write just a goto or a simple for(i){if(i=4)print"Line1";if(i=3)...}

  • The most upvoted answer in 2 weeks wins this.

  • Your output MUST be Line4 Line3 Line2 Line1 OR Line4Line3Line2Line1 OR Line4\nLine3\nLine2\nLine1(where \n is a newline), and it must be generated only by executing those prints backwards.

Happy coding!

UPDATE: Contest is over! Thank you all :)

share|improve this question
Does Arabic count? : ) – dimension10 Feb 13 '14 at 8:17
If you are able to meet the specs, of course :P – Vereos Feb 13 '14 at 10:34
Wanted to quickly clarify one rule... When you say "Every like can contain only one print", do you mean one text line in the code file or one LOC/statement? – Ruslan Feb 15 '14 at 8:54
Every line of code can contain only one print – Vereos Feb 15 '14 at 15:07
does it have to pass a code review - suitable for production code? – Lance Feb 17 '14 at 19:37

148 Answers 148

up vote 161 down vote accepted

Commodore 64 BASIC

40 print "Line 1"
30 print "Line 2"
20 print "Line 3"
10 print "Line 4"
share|improve this answer
I never could figure why line numbers are needed, until now. – ugoren Feb 13 '14 at 9:11
I was going to propose, copying Character ROM ($D000) to RAM ($3000), swapping character bitmaps for "1"<->"4" and "2"<->"3", then running the program in forward order. This is cuter. – Mark Lakata Feb 14 '14 at 1:08
I'm pretty sure you can't actually save/load or otherwise list the code in the order shown using the standard tools (definitely can't on Apple II anyway), all you could do would be type those lines in to the console in that order. And if that's allowed couldn't you just use e.g. C# SendKeys library to type code in any of the answered languages in a different order with arrow keys to move around. – Lance Feb 19 '14 at 22:55


Abusing precedence... :-)

!print "Line1\n".
!print "Line2\n".
!print "Line3\n".
!print "Line4\n";
share|improve this answer
In PHP, print may be used as an expression, as it may be in perl, the return value of which is always 1. !1 returns bool(false), which when typed as a string returns the empty string. A more proper restriction for PHP might be to require echo rather than print; the above really is only one statement. – primo Feb 13 '14 at 6:10
@kuldeep.kamboj It's just grouped that way: print ("Line 1". !print ("Line2". !print ("Line 3". !print "Line4"))); — everything that's on the right of a print statement is part of it. – bwoebi Feb 13 '14 at 8:18
It seems to work in every version very impressive! – eisberg Feb 13 '14 at 13:33
Took me a while to understand (Thanks @eisberg for the link!) but I get it now. While the first print is called first, it doesn't finish evaulating what it needs to print until the inner (lower) prints have already been called and fully evaluated. And the !s are just to hide the 1's that would print otherwise. Brilliant, @bwoebi! – sfarbota Feb 13 '14 at 17:41
@sfarbota Reading rules is hard. Fixed. Thank you :-) – bwoebi Feb 13 '14 at 18:38


Undefined behavior is the most exciting kind of behavior!

   f(printf("Line 1\n"), 
     printf("Line 2\n"), 
     printf("Line 3\n"), 
     printf("Line 4\n"));

Actual output may vary depending on your compiler, linker, operating system, and processor :)

share|improve this answer
I have absolutely no idea how come this actually works, +1. – svick Feb 12 '14 at 18:39
@svick: to support varargs, most C compilers put function arguments on the stack in reverse order (so the top item on the stack is always the 1st argument), which means they're likely to evaluate arguments in the same way. Of course, this assumes arguments are passed on the stack which becomes less and less the case with newer compilers. – Guntram Blohm Feb 12 '14 at 21:53
As @GuntramBlohm said, the basic idea is that C function parameters are often (but not always) pushed onto the stack in a right-to-left order. Since these are function calls, the functions are probably (but not necessarily) called from right-to-left as well. All this is not defined by the C standard though, so while it happens to yield the right result in GCC 4 it's totally up to the compiler and calling convention what actually happens. – Nick Feb 13 '14 at 21:21
@fluffy: Alas, it is the other way around: C does not treat arglist commas as sequence points, unlike other commas. – Williham Totland Feb 14 '14 at 15:08
@WillihamTotland well then I know of some code that I really need to fix... thanks – fluffy Feb 14 '14 at 23:12


Using reflection

public class ReversePrint {
    public static void main(String[]a) {
    static {
            Field f=String.class.getDeclaredField("value");
            f.set("Line3","Line2 ".trim().toCharArray());
            f.set("Line4","Line1 ".trim().toCharArray());
        }catch(Exception e){}



An explanation of why this works can be found here.

share|improve this answer
Horrible. I like it. – Roger Lindsjö Feb 12 '14 at 17:20
+1 People always are saying that java Strings are immutable. You prove that they aren't. – Victor Stafusa Feb 13 '14 at 4:46
This is delightfully nasty, but the requirement of reverse execution is not met. – Thorbjørn Ravn Andersen Feb 13 '14 at 9:29
@ThorbjørnRavnAndersen shhhh... your not supposed to tell them that. :p – Danny Feb 13 '14 at 13:12
@Victor In Java, Strings are immutable. All over Stackoverflow, there are questions like "I thought Strings were immutable". They use reflection and it makes them seem immutable. Java's promises work like this: "If you use our things / classes in the way we intended, then we promise that our claims are correct." Reflection is not the way classes are intended to use. – Justin Feb 15 '14 at 19:37

C (and sort-of Python)

New version, using a macro to fit the question format perfectly. Following Quincunx's comment, I added return to make it nicer.

It also works in Python, but it prints in correct order.

#define print"\n",printf(
#define return"\n"))));}
#define def main(){0?

def main():
    print "Line 1"
    print "Line 2"
    print "Line 3"
    print "Line 4"


Original version - the two are practically the same, after macro substitution:

    printf("Line 1\n",
    printf("Line 2\n",
    printf("Line 3\n",
    printf("Line 4\n",
share|improve this answer
+1 for the macro. Maybe include another one; something like #define } 0)))); (I don't know exactly how macros work in C). That way you could just have the print statements in the main method, nothing else. – Justin Feb 13 '14 at 18:55
@Quincunx, you can't define }, but you can define return, which I now did. It's almost a polyglot now - the print syntax works in several script languages, #define is often a comment, but main(){..} doesn't work in any language I could find. – ugoren Feb 13 '14 at 20:44
@Quincunx, and now it's really a polyglot. – ugoren Feb 13 '14 at 20:50
how is the first two defines work without spaces? Would it make print to be replaced by "\n",printf(? – Lưu Vĩnh Phúc Jun 9 '14 at 11:18
@LưuVĩnhPhúc - The space is optional. It replaces as you say. – ugoren Jun 9 '14 at 12:06


  int i = 0;
  for(; i == 0; printf("Line 1\n"))
    for(; i == 0; printf("Line 2\n"))
      for(; i == 0; printf("Line 3\n"))
        for(; i == 0; printf("Line 4\n"))
          i = 1;
share|improve this answer


print 'Line1' unless
print 'Line2' unless
print 'Line3' unless
print 'Line4'

Edit: Alternatively,

def method_missing(meth,*)
  puts meth.to_s.sub('print'){}

share|improve this answer
I prefer this because it has meth – Ray Koopa Feb 12 '14 at 14:47
Wouldn't you normaly post two answers if you had two solutions? – TheConstructor Feb 12 '14 at 15:30
Wouldn't this look more ruby-ish with code blocks? – manatwork Feb 12 '14 at 15:37
@PacMani those parens don't use white space, they use White space. – corsiKa Feb 12 '14 at 18:22
@manatwork nice one! I do think method_missing is pretty Ruby-ish itself, though. – histocrat Feb 12 '14 at 22:14

ES6 (using backwards mode ;)

Wow, it looks like the designers of ECMAScript had some incredible foresight when they made backwards mode part of the spec:

// activate backwards mode:
'use backwardsˈ; \* mode backwards in now *\
code of lines some ⧵\
\*code*\ "Line1" print \*code*\
\*code*\ "Line2" print \*code*\
\*code*\ "Line3" print \*code*\
\*code*\ "Line4" print \*code*\
code of lines some ⧵\
⁏ˈforwards useˈ // back to ˈnormal'.

// So simple! No need to do anything this complicated:

Output (evaluation, really):


Note that it's exactly of the form requested, with only slight backwardification to fit the syntax of the mode. Note also that this mode is only supported in recent versions of Firefox at the moment.

Final note: Actually, there is no backwards mode. But this is still a valid script that runs in Firefox (copy the whole thing). :D

ES6 "lax mode"

BONUS: Here's an updated version that doesn't use backwards mode, but uses the newly-specified "lax mode" where the JS engine will just try to guess what the code is supposed to do, regardless of adherence to any specified JS syntax (basically the antithesis of strict mode):

// activate "lax" mode:
`use laxˋ; // also works: ˋuse relaxˋ, ˋuse guessingˋ, ˋuse whatevsˋ, etc.
//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code
ˋuse normalˋ; // same as ˋuse default`.

// Again, compare to inferior, illegible "traditional" ES6:

Please note that "lax mode" is currently only available in Firefox >= 34. ;P

share|improve this answer
All 3 links you posted are leading to 404. Is this kind of joke? – manatwork Feb 13 '14 at 13:04
Ah. I see now. The syntax highlighter was your accomplice here. – manatwork Feb 13 '14 at 14:34
This is a combo popularity-contest and code-trolling, no? :) I love it. – Not that Charles Feb 14 '14 at 15:55
This is a phenomenal abuse of Javascript. I like it. – Seiyria Feb 14 '14 at 16:11
Sneaky. Soooo sneaky.... – David Conrad Feb 18 '14 at 19:37


I know, this is madness...

goto d;
a: print "Line1\n"; goto end;
b: print "Line2\n"; goto a;
c: print "Line3\n"; goto b;
d: print "Line4\n"; goto c;
end: exit;
share|improve this answer
That noise you hear is Dijkstra spinning in his grave. :-) – Gareth Feb 12 '14 at 12:21
Thought somebody said "be creative and avoid to write just a goto" ;-) – TheConstructor Feb 12 '14 at 15:29
@TheConstructor The creative part is using goto in PHP ;) – NikiC Feb 12 '14 at 18:54
So full of win. – Nick T Feb 12 '14 at 20:36


use threads;

$a=threads->create(sub {sleep(5); print("Line1\n");});
$b=threads->create(sub {sleep(4); print("Line2\n");});
$c=threads->create(sub {sleep(3); print("Line3\n");});
$d=threads->create(sub {sleep(2); print("Line4\n");});

share|improve this answer
+1, I like this one – Florent Feb 12 '14 at 12:21
This is theoretically not guaranteed to print in exact reverse order. – Cruncher Feb 12 '14 at 16:12
@Cruncher I know, but with 1 second gaps the chances of it printing in anything other than reverse order are pretty slim. – Gareth Feb 12 '14 at 16:13
@Gareth That's why I italicized theoretically :) – Cruncher Feb 12 '14 at 16:20
@Cruncher Isn't that what makes it so fun? – Pierre Arlaud Feb 17 '14 at 9:37


This is almost idiomatic Haskell, as the program now looks like a right-to-left function composition. If the function wasn't print, but something that would return a (useful) value the operator declaration would be unnecessary and the code would be something you'd see in libraries.

a << b = (const a =<< b)

main = putStrLn "Line1"
    << putStrLn "Line2"
    << putStrLn "Line3"
    << putStrLn "Line4"
share|improve this answer
tip: (<<) = flip (>>) – Bergi Feb 12 '14 at 20:26
@Bergi That's another way to write it, I guess a little more elegant even. I was actually a little surprised to see the thing wasn't defined in prelude (or Control.Monad) – shiona Feb 12 '14 at 23:50
@shiona:Yeah, it's a surprising thing to miss. Happily, we have both operators for Applicatives: <* and *>. – Tikhon Jelvis Feb 13 '14 at 12:42
@TikhonJelvis actually, the <* applicative operator is different than this << : a <* b is equivalent to do x<-a;b;return x , i.e. it runs a's effect first – proud haskeller Dec 1 '14 at 21:37


<p>Line 1</p>
<p>Line 2</p>
<p>Line 3</p>
<p>Line 4</p>


body {margin-top:7em}
p + p {margin-top:-4em}

See jsFiddle.

To conform to the rules better, here is a variant in XML, that actually uses print.

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="style.css"?>
  <print>Line 1</print>
  <print>Line 2</print>
  <print>Line 3</print>
  <print>Line 4</print>

where style.css should be

* {display:block; margin-top:3em}
print + print {margin-top:-3em}

HTML without CSS

And for the heck of it, here's one without CSS.

<tfoot><tr><td><table><tfoot><tr><td>Line 1</tr></tfoot>
<tbody><tr><td>                      Line 2</table></tfoot>
<tbody><tr><td><table><tfoot><tr><td>Line 3</tr></tfoot>
<tbody><tr><td>                      Line 4</table></tbody>


share|improve this answer
Can anybody explain the downvote? This does work when printing, you know. – Mr Lister Feb 14 '14 at 12:42
You can also just do p {float:right;} – Noyo Feb 14 '14 at 12:52
But then the results will all be on one line! – Mr Lister Feb 14 '14 at 12:57
...and that's allowed. :] – Noyo Feb 14 '14 at 14:25
...and that's not disallowed. :D You could also wrap it in a div and add the CSS rule div {float:left}. – Noyo Feb 14 '14 at 15:05


#include <iostream>
#define Q(x,y) x ## y
#define P(x,y) Q(x, y)
#define print S P(s, __LINE__) =
struct S { const char *s; S(const char *s): s(s) {} ~S() { std::cout << s << std::endl; } };
int main() {
    print "Line1";
    print "Line2";
    print "Line3";
    print "Line4";

(Local variables are destroyed in reverse order of declaration.)


#include <iostream>
int main() {
    struct S { void (*f)(); S(void (*f)()): f(f) {} ~S() { f(); } } s[] = {
        {[](){ std::cout << "Line1" << std::endl; }},
        {[](){ std::cout << "Line2" << std::endl; }},
        {[](){ std::cout << "Line3" << std::endl; }},
        {[](){ std::cout << "Line4" << std::endl; }},

(Much the same, but using lambdas and an array data member instead.)

share|improve this answer


main = sequence_ $ reverse [
    putStr "Line1",
    putStr "Line2",
    putStr "Line3",
    putStr "Line4"]
share|improve this answer


setTimeout(function(){console.log("Line 1");},900);
setTimeout(function(){console.log("Line 2");},800);
setTimeout(function(){console.log("Line 3");},700);
setTimeout(function(){console.log("Line 4");},600);
share|improve this answer
Using 1,2,3,4 as timeouts also works for me. (However, I do not know whether this behavior is standardized in ECMAScript.) – ComFreek Feb 12 '14 at 20:06
@ComFreek: setTimeout is standardized in HTML5/timers, not in ES. Also, it specifies a minimum timeout of 4ms :-) – Bergi Feb 12 '14 at 20:32
@Bergi Yep, you are right, of course! HTML Standard - Timers - if anyone is interested. – ComFreek Feb 12 '14 at 20:46
Run this on a slow enough machine (say, an 8086 running several other applications?) and it will fail. (By fail, I mean the order will not be reversed, since it will take >= 100ms to execute each statement. – Jeff Davis Feb 13 '14 at 22:20
@lastr2d2 Simulating a slow computer with while loops is fairly subjective, but I think this would be more like it: Note from… "This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected." – Jeff Davis Feb 14 '14 at 17:41


Trying to make defiance of the tips in the question as creative as possible:

#include <stdio.h>
#define print if (i == __LINE__) puts
static unsigned i;
int main(void) {
  while (--i) {
    print("Line 1");
    print("Line 2");
    print("Line 3");
    print("Line 4");
  return 0;
share|improve this answer
nice abuse of a #define :P +1 – masterX244 Feb 13 '14 at 16:25


Assumes cell-wrapping.

----[> (line 1) .[-]<]++++
---[> (line 2) .[-]<]+++
--[> (line 3) .[-]<]++
-[> (line 4) .[-]<]+

Why it works

The first and last lines compose of a loop that repeats four times (counter = cell0).

Inside the loop, there is a counter variable (cell1) that is increased every run.

Each lines checks if decreasing by four, three, two, or one equals zero. Therefore, on the first run, the counter is one and the last line is executed, on the second run, the third line is executed, etc.

The (line 1) shows where you should make the text that is printed. The arrows in the loops allocate cell2 for this purpose. The [-] cleans out cell2 after you use it.

share|improve this answer


import java.util.concurrent.FutureTask;

public class Print {
  public static void main(String[] args) {
    new FutureTask<PrintStream>(new Runnable() {
      public void run() {
        new FutureTask<PrintStream>(new Runnable() {
          public void run() {
            new FutureTask<PrintStream>(new Runnable() {
              public void run() {
                System.out.append("Line1"); }
            }, System.out.append("Line2")).run(); }
        }, System.out.append("Line3")).run(); }
    }, System.out.append("Line4")).run();

It's all in the right timing... ;-)

share|improve this answer
The lines have to be adjacent. – Timtech Feb 12 '14 at 15:09
They are no less adjacent than e.g. with nobody said they should look the same. Will remove some newline-characters ;-) – TheConstructor Feb 12 '14 at 15:13
Okay, great :-) – Timtech Feb 12 '14 at 15:14

Python 3

import atexit

share|improve this answer


In memory of the revered SleepSort and SleepAdd, I present to you... SleepReverse:


function print(){(sleep $((4-$1));echo "Line $1";)&}

print 1
print 2
print 3
print 4
share|improve this answer
For it to look more like the specs, use $1 and $2: function print(){(sleep $((4-$2));echo "$1 $2";)&}; print Line 1 – ThinkChaos Feb 25 '14 at 19:35


Another eval variant:

$lines=array_slice(file(__FILE__),-4); // get last 4 lines of current file
eval(implode('',array_reverse($lines)));exit; // eval lines reversed and exit
print "Line1\n";
print "Line2\n";
print "Line3\n";
print "Line4\n";
share|improve this answer
Slick! Nonetheless, I feel compelled to point out this is a really bad idea. – David Kryzaniak Feb 12 '14 at 22:53

Common Lisp № 1

It's easy to write a ngorp macro that executes its forms in reverse order:

(macrolet ((ngorp (&body ydob) `(progn ,@(reverse ydob))))
   (write-line "Line 1")
   (write-line "Line 2")
   (write-line "Line 3")
   (write-line "Line 4")))
Line 4
Line 3
Line 2
Line 1

Common Lisp № 2

Here's one that takes the problem very literally; the code from the question appears in program without modification:

(macrolet ((execute-prints-backwards (&body body)
                ,@(nreverse (mapcar (lambda (string)
                                      (list 'write-line string))
                                    (remove-if-not 'stringp body))))))

//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code

share|improve this answer

Go (Golang)

package main

import "fmt"

func main() {
    defer fmt.Println("Line 1")
    defer fmt.Println("Line 2")
    defer fmt.Println("Line 3")
    defer fmt.Println("Line 4")

Try it out:

share|improve this answer
I wanted to post the exact same code. Literally, byte-for-byte exactly the same. – Art Feb 13 '14 at 15:08
@Art, awesome! I hope to see more Go used in Code Golf. – cory.todd Feb 13 '14 at 19:18
Probably won't happen. Go isn't really good a being compressed, they deliberately limit weird constructs so that you can't create an unreadable mess. But in this case (and maybe other popularity contests) it has a chance. – Art Feb 14 '14 at 8:40


Here comes the double-faced script:

if [ $s -ne 0 ]; then tac $0 | bash; exit; fi
echo "Line1"
echo "Line2"
echo "Line3"
echo "Line4"
share|improve this answer
I never even knew tac existed! Haha, thanks. – Noyo Feb 14 '14 at 10:25


let inline (?) f g x = g x; f x

(printfn "Line1%s") ?
 (printfn "Line2%s") ?
  (printfn "Line3%s") ?
   (printfn "Line4%s") ""

Just created a custom operator that executes functions in reverse order.

share|improve this answer
I am pretty sure (?) f(g(x)) = g(x); f(x) is calculus and not programming. – Jeff Davis Feb 13 '14 at 22:27
@JeffDavis: Pretty sure (?) f g x reads roughly as (?)(f, g, x), not f(g(x)) – Eric Feb 17 '14 at 0:41


print("Line4") or '') or '') or '')

Can be 6 bytes shorter by removing all spaces in last line.

share|improve this answer


echo off

call :revers ^
echo.line1 ^
echo.line2 ^
echo.line3 ^

if not "%2"=="" call :revers %2 %3 %4 %5 %6 %7 %8 %9
share|improve this answer
Welcome to codegolf! Nice post. – Cruncher Feb 13 '14 at 16:33


Instead of directly calling the Run method, I'm creating a dynamic method that contains a copy of Run's IL bytecode, except that the load-string opcode operands are swapped. Which causes the new method to display the strings in reverse order.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace TestApp
    class Program
        public static void Run()
            Console.WriteLine("Line 1");
            Console.WriteLine("Line 2");
            Console.WriteLine("Line 3");
            Console.WriteLine("Line 4");

        static void Main(string[] args)
            var method = typeof(Program).GetMethod("Run");
            var il = method.GetMethodBody().GetILAsByteArray();
            var loadStringOperands = new Stack<int>();
            for (int i = 0; i < il.Length; i++)
                if (il[i] == OpCodes.Ldstr.Value)
                    loadStringOperands.Push(BitConverter.ToInt32(il, i + 1));
                    i += 4;

            var run = new DynamicMethod("Run", typeof(void), null);
            var gen = run.GetILGenerator(il.Length);
            for (int i = 0; i < il.Length; i++)
                if (il[i] == OpCodes.Ldstr.Value)
                    var str = method.Module.ResolveString(loadStringOperands.Pop());
                    gen.Emit(OpCodes.Ldstr, str);
                    i += 4;
                else if (il[i] == OpCodes.Call.Value)
                    var mInfo = method.Module.ResolveMethod(BitConverter.ToInt32(il, i + 1)) as MethodInfo;
                    gen.Emit(OpCodes.Call, mInfo);
                    i += 4;
                else if (il[i] == OpCodes.Ret.Value)

            run.Invoke(null, null);
share|improve this answer


yet another solution using eval()

a = [

for line in reversed(a):

it's not very complex, but easy to understand.

share|improve this answer
the only code I understand :D – moldovean Feb 13 '14 at 8:31




#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<std::function<void()>> functors;
    functors.push_back([] { std::cout << "Line1"; });
    functors.push_back([] { std::cout << "Line2"; });
    functors.push_back([] { std::cout << "Line3"; });
    functors.push_back([] { std::cout << "Line4"; });
    std::for_each (functors.begin(), functors.end(), [](std::function<void()> f) {f();});
    return 0;
share|improve this answer
Instead of the std::reverse and std::for_each, simply use while (! functors.empty()) { functors.back()(); functors.pop_back(); } – David Hammen Sep 5 '15 at 18:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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