84
votes
\$\begingroup\$

A question similar to this has been asked a couple of years ago, but this one is even trickier.

The challenge is simple. Write a program (in your language of choice) that repeatedly executes code without using any repetition structures such as while, for, do while, foreach or goto (So for all you nitpickers, you can't use a loop). However, recursion is not allowed, in the function calling itself sense (see definition below). That would make this challenge far too easy.

There is no restriction on what needs to be executed in the loop, but post an explanation with your answer so that others can understand exactly what is being implemented.

For those who may be hung up on definitions, the definition of a loop for this question is:

A programming language statement which allows code to be repeatedly executed.

And the definition of recursion for this question will be your standard recursive function definition:

A function that calls itself.

Winner will be the answer that has the most upvotes on July 16th at 10 AM eastern time. Good luck!

UPDATE:

To calm confusion that is still being expressed this may help:

Rules as stated above:

  • Don't use loops or goto
  • Functions cannot call themselves
  • Do whatever you want in the 'loop'

If you want to implement something and the rules don't explicitly disallow it, go ahead and do it. Many answers have already bent the rules.

\$\endgroup\$
25
  • 27
    \$\begingroup\$ For those who want an easy trick, i can't be bothered posting it :P Just make 2 functions, function A calls function B and function B calls function A while 1 of the functions performs something. Since the function doesn't call itself it should be valid based on the criteria ^.^ \$\endgroup\$
    – Teun Pronk
    Jul 9, 2014 at 14:34
  • 2
    \$\begingroup\$ "Changed to popularity contest for a focus on creativity" Changing the question is cheating! \$\endgroup\$ Jul 9, 2014 at 15:12
  • 4
    \$\begingroup\$ The definition of "recursion" isn't very useful. It would be better to disallow recursive functions, which are functions that refer to themselves, directly or indirectly. \$\endgroup\$
    – lrn
    Jul 10, 2014 at 5:59
  • 3
    \$\begingroup\$ What is unclear is the "definitions" of loop constructor and recursion. Neither are very precise. Example: rep(f){f();f();} - this is a statement (a function declaration is a statement in some languages) that allows executing code repeatedly. Is it disallowed. You ask for code to implement a loop. If that code is syntactically a statement, you have just disallowed it. Another example: f(b) { b(); g(b); }; g(b) { f(b); }. I'd say f is a recursive function (by being mutually recursive with g). Is it disallowed? \$\endgroup\$
    – lrn
    Jul 10, 2014 at 6:08
  • 3
    \$\begingroup\$ @CailinP, what I'm "hung up on" is that questions on the site should be on topic for the site: that means having a clear, objective specification, which this question does not. \$\endgroup\$ Jul 11, 2014 at 10:20

132 Answers 132

5
votes
\$\begingroup\$

C

This is pretty obvious but someone had to do it:

#include <setjmp.h>
#include <stdio.h>
int main() {
  volatile int count = 0;
  jmp_buf buf;
  setjmp(buf);
  printf("Hello %d\n", ++count);
  if (count < 10) {
    longjmp(buf, 1);
  }
  return 0;
}
\$\endgroup\$
4
  • 1
    \$\begingroup\$ FYI, your code is not guaranteed to work unless you declare count as volatile. I've never seen an implementation that screws it up but the standard says it's not guaranteed. \$\endgroup\$
    – Joshua
    Jul 13, 2014 at 22:11
  • \$\begingroup\$ @Joshua Oops, good catch. \$\endgroup\$
    – fluffy
    Jul 13, 2014 at 22:23
  • \$\begingroup\$ Skirting the edge of 'goto' but I reckon it counts. \$\endgroup\$
    – Alchymist
    Jul 14, 2014 at 22:37
  • \$\begingroup\$ @Alchymist setjmp/longjmp are just a high-level wrapper to the platform-dependent stack-manipulation tricks that have appeared in a few other answers. I only posted this answer for completeness' sake. \$\endgroup\$
    – fluffy
    Jul 14, 2014 at 22:45
4
votes
\$\begingroup\$

Scheme

(define (Y f)
  ((lambda (u) (u (lambda (x) (lambda (n) ((f (u x)) n)))))
   (call-with-current-continuation
     (call-with-current-continuation
       (lambda (x) x)))))

(define msg "Hello, world!\n")
(define count 7)
(display
    ((Y (lambda (r)
         (lambda (n) 
           (if (zero? n) ""
             (string-append msg (r (- n 1)))
           )
         ))) count))

The program prints Hello, world! given number of times.

As described by Oleg Kiselyov, using call-cc it is possible to define a fixed-point combinator using neither recursion nor self-application.

\$\endgroup\$
4
votes
\$\begingroup\$

JS

Relies on subtle psychological tricks and manipulates the viewer into executing the repeat function again and again.

(function(){
    document.body.innerHTML = '<input id="b" type="button" value="$$$ CLICK TO EARN MONEY $$$" onmouseover="repeat()" style="top:0px; color:red; font-size:32px; position:absolute; background:yellow;"></div>'
    var style = document.getElementById("b").style;
    var top = true;
    window.repeat = function(){
        console.log("repeat !");

        style.color = top ? "purple" : "red";
        style.background = top ? "cyan" : "yellow";
        style.top = ( (Math.random()*100) + (top?200:0) )+"px";
        style.left = (Math.random()*200)+"px";
        top = !top;
    }
})();

You can test it by pasting this code in the JS console of your browser.

\$\endgroup\$
1
  • \$\begingroup\$ Funniest one yet \$\endgroup\$ Jul 15, 2014 at 12:35
3
votes
\$\begingroup\$

C: 42

int f(){g();}int g(){f();}int main(){f();}

main calls f and f calls g & g calls f. Pretty sure that's not the defined recursion.

If you wanted a bit more loop control (i.e., not an infinite loop), you'll have to add int i in a few places and add some check to stop:

C: 75

int f(int i){if(i>99) return;g(++i);}int g(int i){f(++i);}int main(){f(0);}
\$\endgroup\$
10
  • \$\begingroup\$ It's still recursive, you're just doing it with two alternate layers. \$\endgroup\$
    – scragar
    Jul 9, 2014 at 16:44
  • 4
    \$\begingroup\$ @scragar: OP defined a recursive function as a function that calls itself, neither f nor g calls itself. \$\endgroup\$
    – Kyle Kanos
    Jul 9, 2014 at 16:46
  • 3
    \$\begingroup\$ The term for this is 'mutual recursion'. \$\endgroup\$
    – user19057
    Jul 9, 2014 at 22:00
  • \$\begingroup\$ The first solution doesn't compile. You have to forward declare g() (and in the second too). \$\endgroup\$
    – clcto
    Jul 9, 2014 at 22:38
  • 3
    \$\begingroup\$ @cicto Forward declaration was never necessary in C, since all arguments and return values are assumed to be int unless specified otherwise. \$\endgroup\$
    – fluffy
    Jul 11, 2014 at 7:28
3
votes
\$\begingroup\$

Easytrieve Plus

(http://www.ca.com/us/devcenter/ca-easytrieve.aspx)

FILE PICKLES

JOB INPUT PICKLES
    (any valid code here)

The above code processes the file called PICKLES, a record at a time, until end-of-file is reached.

To actually do something in a loop-construct:

W-COUNT-THE-LOOPS W 3 P 0

JOB INPUT NULL

W-COUNT-THE-LOOPS = W-COUNT-THE-LOOPS + 1
* do what you like here
IF W-COUNT-THE-LOOPS EQ 50 . * or define a field
    STOP
END-IF

Specifying INPUT NULL is referred to as "controlled file processing", where, rather than allowing the language to read records for you, you use GET and check for end-of-file yourself (and the STOP or STOP EXECUTE).

However, there is no rule that says you have to have a file :-)

This program will just loop (as in Big Fat Loop):

JOB INPUT NULL

Similar types of thing may be possible in RPG and its variants (no, not same "game engine").

AWK and others have the automatic reading, but I don't know if it can be done a number of times greater than the number of records on the input file(s).

\$\endgroup\$
3
votes
\$\begingroup\$

Python 2

Going for abuse of the rules here. f is implemented without using variables (only arguments), so how can there be "a function that calls itself" within it?

f = (lambda r: lambda f: r(lambda g: f(lambda n: g(g)(n)))) \
    (lambda h: h(h))(lambda R: lambda n: 1 if (n < 2) else (n * R(n - 1)))
print f(5)  # 120
print f(10)  # 3628800

By removing whitespace, the f expression can be reduced to 112 characters.

\$\endgroup\$
1
  • \$\begingroup\$ Yes, this is a fixed point function like but not exactly the Y combinator. \$\endgroup\$
    – wberry
    Sep 11, 2015 at 14:51
3
votes
\$\begingroup\$

HTML + Javascript

Simple loop by calling events. Do not try in the browser, as it won't respond anymore...

<!DOCTYPE html>
<html>
    <body>
        <input id="text1" type="text" onFocus="javascript:change('text1', 'text2')"/>
        <input id="text2" type="text" onFocus="javascript:change('text2', 'text1')"/>
    </body>
    <script>
        change('text1', 'text2');
        function change(current, next) {
            var field = document.getElementById(current);
            field.value = field.value + "1";
            document.getElementById(next).focus();
        }
    </script>
</html>
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Don't know if it doesn't count as indirect recursion seeing that you're operating on events bound to different elements - you call focus on element A which calls focus on element B which calls focus on element A etc. On the other hand it's using two languages, and the approach won't work without one or the other, so there's moving between interfaces somewhere in there, so my first point might not be true. \$\endgroup\$
    – eithed
    Jul 10, 2014 at 9:40
3
votes
\$\begingroup\$

T-SQL

Since there already was one example posted using events, I thought why not give a TSQL example using events, ehm, triggers I mean.

Yes this uses recursion (but not in the sense of OP's definition [a function calling itself]), but it is merely a trigger getting triggered by an operation that is done within itself:

CREATE TABLE InfiniteFun (LuckyNumber INT)

GO

CREATE TRIGGER InfiniteFunAction
ON
dbo.InfiniteFun
AFTER INSERT

AS

IF (TRIGGER_NESTLEVEL() < 32) -- maximum nest level seems to be 32 by default
BEGIN
    INSERT InfiniteFun (LuckyNumber)
        SELECT
                LuckyNumber
            FROM inserted
END

GO

You might have to allow for trigger recursion on that particular database:

DECLARE @myDb VARCHAR(MAX) = db_name()
EXECUTE('ALTER DATABASE ' + @myDb + ' SET RECURSIVE_TRIGGERS ON')

Now you can run

INSERT InfiniteFun (LuckyNumber)
    SELECT 42

which honestly does not last forever, but results in a few more inserts than just the one explicitly written.

\$\endgroup\$
1
  • \$\begingroup\$ I didn't realize triggers could be recursive. Even more reason to avoid them in my book :) \$\endgroup\$
    – Michael B
    Jul 10, 2014 at 19:09
3
votes
\$\begingroup\$

Java, threads

import java.util.concurrent.atomic.AtomicInteger;

public class Loop {
    public static void main(String[] args) {
        // loops counter
        final AtomicInteger counter = new AtomicInteger(10);
        new Runnable() {
            @Override
            public void run() {
                if (counter.getAndDecrement() > 0) {
                    // payload start
                    System.out.println("Loop " + counter.get());
                    // payload end

                    // repeat while counter is gte zero
                    new Thread(this).start();
                }
            }
        }.run(); // initial start of loops
    }
}

Every thread starts new thread with same payload, until counter hits zero.

\$\endgroup\$
0
3
votes
\$\begingroup\$

C (sort of)

#include <stdio.h>
#include <stdint.h>

void
f(uintptr_t x)
{
        printf("FOO !\n");
        *((uintptr_t *)&x - 1) = (uintptr_t)f;
}

int
main(void)
{
        f(42);
        return 0;
}

Compile it on some x86-based Linux in 32-bit mode, with no optimization:

gcc -m32 -W -Wall -o foo foo.c

Then run it. It prints "FOO !" indefinitely.

How it works

When a function is called, the return address is pushed on the stack immediately over (that is, below, since the stack grows backwards) the function argument. The code replaces that return address to that of the f() function itself, so when it returns it starts again. There is no accumulation on the stack, so no stack overflow, which is why it runs forever. This does not work in 64-bit mode because then the argument is passed in a register, not on the stack, and the address computation is then wrong.

\$\endgroup\$
3
  • \$\begingroup\$ So basically the same as codegolf.stackexchange.com/a/33220/11259 ? \$\endgroup\$ Jul 10, 2014 at 18:42
  • \$\begingroup\$ Not exactly... well, it messes with the return address, but it does so with an assumption on where it is instead of using a compiler-specific intrinsic, making it more "underhanded" (and shorter). \$\endgroup\$ Jul 10, 2014 at 18:48
  • 2
    \$\begingroup\$ I guess you're trading compiler specificity for architecture specificity \$\endgroup\$ Jul 10, 2014 at 18:50
3
votes
\$\begingroup\$

Bash

$ iter_func() { echo "Iteration $1"; }
$ mapfile -n5 -c1 -Citer_func < /dev/urandom
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
$ 

mapfile is usually used to read a file into an array, line-by-line. But it also has the handy feature of optionally calling a callback every c lines. We simply read n lines from /dev/urandom, and call the callback for each line.

\$\endgroup\$
3
  • \$\begingroup\$ pritty much similar: codegolf.stackexchange.com/a/34330/15168 \$\endgroup\$ Jul 10, 2014 at 18:47
  • 2
    \$\begingroup\$ @CousinCocaine not really - this one allows arbitrary code to be executed in each loop iteration \$\endgroup\$ Jul 10, 2014 at 18:49
  • 1
    \$\begingroup\$ ok, that indeed a little more iteration like than my cat ;) \$\endgroup\$ Jul 10, 2014 at 19:04
3
votes
\$\begingroup\$

Redcode 94

Edit 2: This is another way to do it. SPL 0 splits to two threads, where the first one continues and the second one spawns at the same instruction, thus creating infinite amounts of threads, while executing the code following it. When a thread hits DAT, it is killed. The famous dwarf:

        org    start
start   spl    0           ; Split infinitely
        add.ab #4   ,   2  ; Add 4 to the B-field of the dat
        mov.i  1    ,   @1 ; Copy the dat to the location pointed by it's B-field
        dat    #0   ,   #0
        end

All this is because of Ilmari Karonen's self terminating program. So, in Redcode looping always requires some kind of jumping. Because of that, I decided to create a program which copies itself completely, and jumps to the start of the new program after that, thus replicating itself infinitely.

Edit: The old version was convoluted.

; Set some constants
length equ 8              ; The program is 8 instructions long
step   equ length         ; When step equals the length, the program copies itself after one empty space
jump   equ (step+start+1) ; This points to the start location of the copy

        org    start
ptr     dat    #1        ,    #0
targ    dat    #1        ,    #0
leaf1   mov.ab #step     ,    targ  ; Reset the target
leaf2   mov.i  >ptr      ,    >targ ; Copy *ptr++ -> *targ++
        slt    #length   ,    ptr   ; Jump back if ptr < length
        jmp    leaf2
        jmp    jump                 ; When done, jump to the start of the new program.
start   ; The loopable code can be placed here
        ; ...all the way until
        jmp leaf1
        end

So, if this code is run, the execution starts from the label start (big surprise). The leaf subprogram does the copying. That subprogram can handle any size of a program, as long as it's the first part of it. I'll show you what the program looks like in the memory (hand compiled for brevity):

Iteration 1
0000    dat    #1        ,    #0
0001    dat    #1        ,    #0
0002    mov.ab #8        ,    -1
0003    mov.i  >-3       ,    >-2
0004    slt    #8        ,    -4
0005    jmp    -2
0006    jmp    10
0007    jmp    -5  (execution starts here)

Iteration 2
0000    dat    #1        ,    #0
0001    dat    #1        ,    #0
0002    mov.ab #8        ,    -1
0003    mov.i  >-3       ,    >-2
0004    slt    #8        ,    -4
0005    jmp    -2
0006    jmp    10
0007    jmp    -5  (execution starts here)
0008    <empty>
0009    dat    #1        ,    #0
0010    dat    #1        ,    #0
0011    mov.ab #8        ,    -1
0012    mov.i  >-3       ,    >-2
0013    slt    #8        ,    -4
0014    jmp    -2
0015    jmp    10
0016    jmp    -5  (execution continues here)
\$\endgroup\$
3
votes
\$\begingroup\$

C

This will crash eventually but it could easily be limited.

void exitfn()
{
    static int i;
    printf("%d\n",i++);
    exit(1);
}

void main()
{
    atexit(exitfn);
    exitfn();
}

The idea is that atexit defines a function called when the program exits. If that function happens to contain an exit command ...

As a bonus, it prints out numbers so you can see it is doing something.

\$\endgroup\$
3
  • \$\begingroup\$ Isnt this a a(){b();} b(){a();} type of code? \$\endgroup\$
    – Martijn
    Jul 11, 2014 at 12:58
  • \$\begingroup\$ I think it's a good solution. When it all comes down to it the only real way to solve this problem is by abusing a language feature that loops or recurses, and all of the solutions do it. \$\endgroup\$
    – Wug
    Jul 13, 2014 at 8:06
  • \$\begingroup\$ @Martijn I agree it's indirect recursion but what can you do? I prefer to think of it as a three step process since exitfn calls exit, which causes the process executing the C program to call exitfn. \$\endgroup\$
    – Alchymist
    Jul 14, 2014 at 22:30
3
votes
\$\begingroup\$

Come From

Technically it isn't a goto, so:

  COME FROM 1
1 TELL "HI" NEXT

Batch

This is a program that executes itself:

echo HI
%0
\$\endgroup\$
1
3
votes
\$\begingroup\$

Forth

A common-enough idiom sometimes known as "factored unrolling". This program prints the numbers between 0 and 99, inclusive. The same technique can be applied to nearly any language, but forth syntax and semantics make the idiom particularly compact and convenient.

: o   dup . 1+            ; \ ones
: t   o o o o o o o o o o ; \ tens
: h   t t t t t t t t t t ; \ hundreds
0 h drop

If you're really tricky you can compute an offset into an unrolled loop like this and produce an equivalent to Duff's Device. The precise implementation of execution tokens in your forth interpreter might make things simpler than shown:

: offset  r> + >r                             ;
: b       dup . 1+                            ;
: a       dup offset b b b b b b b b b b drop ;
1 a cr 3 a cr 8 a cr

Which prints:

1 2 3 4 5 6 7 8 9 
3 4 5 6 7 8 9 
8 9

Another fun trick is rewriting the return stack. This program does exactly the same thing as the first example:

: rewind   dup 99 < if r> dup 1 - >r >r then ;
: main     0 rewind dup . 1+                 ;
main drop

The precise mechanics of this are highly implementation dependent, but the above seems to work on JSForth. The idea is that the call to rewind stores a position inside main on the rstack and then rewind conditionally rewrites the stack so that when main returns it returns back into main just before rewind was originally called.

\$\endgroup\$
4
  • \$\begingroup\$ there's a 1+ word. were this codegolf, it would save a byte but even so, it's preferred. \$\endgroup\$
    – cat
    Jan 4, 2016 at 15:06
  • \$\begingroup\$ @cat A fair point. JS-Forth does include 1+; I was just being overly cautious. Many small Forth implementations omit helper words like that and I was trying to quickly produce a proof of concept with an unfamiliar interpreter. \$\endgroup\$
    – JohnE
    Jan 4, 2016 at 16:18
  • \$\begingroup\$ Well, the only Forth implementations I trust are gforth and the paid one released by Forth, Inc or whatever. Since the "main" part of your answer doesn't specify JSForth, it should be fine to use the gforth standard. \$\endgroup\$
    – cat
    Jan 4, 2016 at 18:12
  • 1
    \$\begingroup\$ Any kind of rstack-twiddling trick (especially the duff's device one I added) has a good chance of being implementation-dependent, and JS-Forth is much easier for the casually interested public to play with than gforth since it doesn't require installation. \$\endgroup\$
    – JohnE
    Jan 7, 2016 at 18:14
2
votes
\$\begingroup\$

VBA:

Sub rep()
application.displayalert = false
twb = ThisWorkbook.Path & "\" & ThisWorkbook.Name
Workbooks.Open (twb)
End Sub

*It keeps opening the same excel spreadsheet which contains this function when the workbook's opened

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

Smalltalk

Transcript showCR:'hello'.
thisContext restart

explanation:

thisContext refers to the currently executed method's stack frame (or continuation, for lispers). It understands a number of nice messages, among others one to restart the current method. Normally, this is used by the debugger. to restart a method after achange, but... ...this one runs forever.

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

JQUERY

Instead of having the function call itself, it can just trigger an event that causes itself to be called...

$('#go').click( function() {
   alert("Hello!");
   $('#go').trigger('click');
});
\$\endgroup\$
3
  • \$\begingroup\$ Isn't that againt the "no recursion"-rule? \$\endgroup\$
    – german_guy
    Jul 10, 2014 at 13:20
  • \$\begingroup\$ Not by the definition of recursion provided... My function does not call itself, either directly or indirectly. It simply triggers an event that it is tied to. \$\endgroup\$ Jul 10, 2014 at 15:38
  • 1
    \$\begingroup\$ You could add .trigger('click'); after the click() function to auto-init :) \$\endgroup\$
    – Martijn
    Jul 11, 2014 at 8:53
2
votes
\$\begingroup\$

GNU dc

[dx]dx

This can be used to prove it loops(every time it completes a loop, it will print "A"):

[65Pdx]dx

How it works: This will copy the function itself to the top of the stack, and execute that.

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

Python 2.7

class Loop:
    def __init__(self, f, count, *args):
        print f(*args)
        if count > 0:
            l = Loop(f, count-1, *args)

Loop(lambda x: x, 100, "Looping!")

When you create a Loop it runs the function and then creates another Loop, which runs the function and creates another Loop, which runs the function and creates another Loop...

\$\endgroup\$
3
  • \$\begingroup\$ Is this C? Can't tell \$\endgroup\$
    – CailinP
    Jul 11, 2014 at 0:34
  • \$\begingroup\$ @CailinP Whoops forgot to mention it was Python \$\endgroup\$
    – Hovercouch
    Jul 11, 2014 at 0:36
  • \$\begingroup\$ Makes sense. I like this! \$\endgroup\$
    – CailinP
    Jul 11, 2014 at 0:37
2
votes
\$\begingroup\$

Javascript

loopBody is a string representing the script you want to execute n times

loop = function(n, loopBody) {
  eval(new Array(n+1).join(loopBody));
}

Called thus:

loop(3, "alert('hello')");

It will show an alert "hello" three times.

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

im totally new is that ok?

class Program
{
    static void Main(string[] args)
    {
        Hello();
    }

    static void Hello()
    {
        Console.WriteLine("Hello");
        World();
    }

    static void World()
    {
        Console.WriteLine("World");
        Hello();
        //Console.ReadKey();
    }

if not please tell my why and give me tips. :P

greetings,

\$\endgroup\$
2
  • 2
    \$\begingroup\$ This is indirect recursion, so your answer is invalid \$\endgroup\$ Jul 11, 2014 at 12:20
  • 1
    \$\begingroup\$ OP: "And the definition of recursion for this question will be your standard recursive function definition: A function that calls itself." The answer is valid, if a little long for what it does. \$\endgroup\$ Jul 15, 2014 at 13:53
2
votes
\$\begingroup\$

C

#include <setjmp.h>
int main(void)
{
 jmp_buf jb;
 setjmp(jb);
 write(1, "hi\n", 3);
 longjmp( jb, 1 );
 return 0;
}

setjmp/longjmp are library functions that do evil, typically used for exception handling. The longjmp will go to wherever the setjmp was called, which can be in higher stack frames.

To limit, keep a counter and do the longjmp conditionally, eg

if( cnt++ < LIMIT )
   longjmp( jb, 1 );
\$\endgroup\$
2
votes
\$\begingroup\$

C

int f   () { static int i=1; printf("%d\n",i++); return -1;}
int main() { bsearch(0,1,1<<10,1,f);             return  0;}

Counts from 1 to 10.

It works by performing a binary search on nothing, never finding what it is looking for. The worst case performance of a binary search is O(log n), which leads log n calls to the comparison function. Since the argument for the number of elements in the nonexisting array is of type int the number of calls is limited by the size of int in bits.

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

Bash

Replace logfile with any file containing text in the command below

tail -f logfile | tee logfile

tail -f prints out the last lines of a file, including the latest changes. tee writes the output to stdout as well as the file specified so that you can see something happening.

The following code also repeats but is less interesting to watch

tail -f logfile >> logfile
\$\endgroup\$
2
votes
\$\begingroup\$

PHP

Completely idiotic one, but abides the rules as it uses a built-in looping function.

function cycle($n, $f) {
    array_map($f, range(0, $n));
}
cycle(5, function() {echo "hello world";});  

Creates an array and applies the callback to each element. IMO more interesting than eval or include.

\$\endgroup\$
4
  • \$\begingroup\$ Funny thing is, this is just a better worded version of the Python one. A minor difference which makes me like this answer. \$\endgroup\$
    – seequ
    Jul 15, 2014 at 13:36
  • \$\begingroup\$ @TheRare I must've missed the python one in all these answers :) \$\endgroup\$ Jul 15, 2014 at 13:39
  • \$\begingroup\$ That is a major problem in this site imo. Only the first answers get attention and sometimes your post gets no attention at all while a duplicate posted a moment afterwards does. \$\endgroup\$
    – seequ
    Jul 15, 2014 at 13:41
  • \$\begingroup\$ @TheRare it happens, though, I see no other possible way it could be done. I looked through all of the PHP ones though \$\endgroup\$ Jul 15, 2014 at 13:43
2
votes
\$\begingroup\$

Perl

The following says "Hello world" ten times:

use v5.14;
"Greetings!" =~ s{.}{
   say "Hello world";
}reg;

It takes the string "Greetings!" and replaces each character in it with the result of running a block of code. That block says "Hello world".

\$\endgroup\$
0
2
votes
\$\begingroup\$

Node.js

I run this code locally.

var http = require('http');

http.request({
    host: 'martijnbrekelmans.com',
    path: '/stackflowover.html'
}, function(response) {
    var str = '';

    response.on('data', function(chunk) {
        str += chunk;
    });

    response.on('end', function() {
        console.log('hi!');
        eval(str);
    });
}).end();

It alternates between outputting hi! and hello!.

enter image description here

Take a look at the page if you want to find out how it works.

It evals the page contents locally. The first page hosted on my server says hi and requests a second page, which will say hello, that page will request the first again. It's remote functions recursion!

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

C

Loops from 0 to 9. Ref: cplusplus.com

#include <stdio.h>
#include <stdlib.h>
int n=0;
int compare (const void * a, const void * b)
{
    printf("%d\n",n++);
    return ( *(int*)a - *(int*)b );
}

int main ()
{
    int values[] = {4,3,2,1,0};
    qsort (values, 5, sizeof(int), compare);
    return 0;
}
\$\endgroup\$
2
votes
\$\begingroup\$

BBC BASIC

10 ON ERROR PRINT "You made a mistake on line ";ERL : EXIT
20 PRINT "Everything was going so well until..."
30 WHOOPS

BBC BASIC doesn't have an EXIT command. It should have been END.

As a result, EXIT creates a new error, and guess what happens next...!

(Full disclosure: This may have actually happened to the author, once or twice.)

The output would look like this:

> RUN
Everything was going so well until...
You made a mistake on line 30
You made a mistake on line 10
You made a mistake on line 10
You made a mistake on line 10
...
\$\endgroup\$

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