title: Loop without 'looping'

text:
# Question
Title: Loop without 'looping'
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.

# Answer
> 257 votes
# Ruby

```
def method_missing(meth,*args)
  puts 'Banana'
  send(meth.next)
end

def also
  puts "Orange you glad I didn't say banana?"
end

ahem

```

Demo

Clears its throat, prints "Banana" 3070 times, and also puts "Orange you glad I didn't say banana?".

This uses Ruby's ridiculous just-in-time method definition functionality to define every method that lies alphabetically between the words 'ahem' and 'also' ("ahem", "ahen", "aheo", "ahep", "aheq", "aher", "ahes", "ahet", "aheu", "ahev"...) to first print Banana and then call the next in the list.

# Answer
> 81 votes
# Python - 16

or any other language with eval.

```
exec"print 1;"*9

```

# Answer
> 78 votes
# CSharp

I've expanded the code into a more readable fashion as this is no longer code golf and added an increment counter so that people can actually see that this program does something.

```
class P{
    static int x=0;
    ~P(){
        System.Console.WriteLine(++x);
        new P();
    }
    static void Main(){
        new P();
    }
}

```

(Don't do this ever please).

On start we create a new instance of the `P` class, which when the program tries to exit calls the GC which calls the finalizer which creates a new instance of the `P` class, which when it tries to clean up creates a new `P` which calls the finalizer...

The program eventually dies.

Edit: Inexplicably this runs only around 45k times before dying. I don't quite know how the GC figured out my tricky infinite loop but it did. The short is it seems it didn't figure it out and the thread just was killed after around 2 seconds of execution: https://stackoverflow.com/questions/24662454/how-does-a-garbage-collector-avoid-an-infinite-loop-here

Edit2: If you think this is a little too much like recursion consider my other solution: https://codegolf.stackexchange.com/a/33268/23300

It uses reification of generic methods so that at runtime it constantly is generating new methods and each method in term calls a newly minted method. I also avoid using `reference` type parameters, as normally the runtime can share the code for those methods. With a `value` type parameter the runtime is forced to create a new method.

# Answer
> 52 votes
# Befunge

```
.

```

Good old Befunge outputs 0 (from an empty stack) pretty much forever, as lines wrap around.

# Answer
> 47 votes
**JS**

`(f=function(){ console.log('hi!'); eval("("+f+")()") })()`

Function fun!

A function that creates another function with the same body as itself and then runs it.

It will display hi at the end when the stack limit is reached and the entire thing collapses.

Disclaimer: you'll not be able to do anything in your browser until stack limit is reached.

---

And another one, more **evil**:

`function f(){ var tab = window.open(); tab.f = f; tab.f()}()`

It creates a function which opens up a window, then creates a function within that window which is copy of the function, and then runs it.

Disclaimer: if you'll allow opening of popups the only way to finish this will be to restart your computer

# Answer
> 39 votes
# x86 assembly/DOS

```
    org 100h

start:
    mov dx,data
    mov ah,9h
    int 21h
    push start
    ret

data:
    db "Hello World!",10,13,"$"

```

> Did I say no *reversed tail* recursion? Did I?

### How it works

> The `ret` instruction, used to return from a function, actually pops the return address from the stack (which normally is put there by the corresponding `call`) and jumps to it. Here at each iteration we `push` the entrypoint address on the stack before returning, thus generating an infinite loop.

# Answer
> 37 votes
# Java

Straight from XKCD

It's a never-ending game of catch between a parent and child!

The target of `CHILD` is set to `PARENT` and the target of `PARENT` is the `CHILD`. When the `PARENT` calls `AIM`, it throws the instance of the `BALL` class and it is caught by the catch statement. The catch statement then calls `PARENT.TARGET.AIM` where the target is the `CHILD`. The `CHILD` instance does the same and "throws the ball back" to the parent.

# Answer
> 31 votes
# Bash, 3 characters

```
yes

```

yes will repeatedly return 'y' to the console

Edit: Everyone is encouraged to edit this line:

```
yes something | xargs someaction

```

(thanks to Olivier Dulac)

# Answer
> 28 votes
# C, 35 characters

```
main(int a,char**v){execv(v[0],v);}

```

The program executes itself. I'm not sure if this is considered recursion or not.

# Answer
> 28 votes
# C (with GCC builtins - also seems to work with clang)

* No explicit loops
* No explicit gotos
* No recursion
* Just good old-fashioned messing with the stack (kids, don't try this at home without supervision):

```
#include <stdio.h>

void *frameloop (void *ret_addr) {
    void **fp;
    void *my_ra = __builtin_return_address(0);

    if (ret_addr) {
        fp = __builtin_frame_address(0);
        if (*fp == my_ra) return (*fp = ret_addr);
        else fp++;
        if (*fp == my_ra) return (*fp = ret_addr);
        else fp++;
        if (*fp == my_ra) return (*fp = ret_addr);
        else fp++;
        if (*fp == my_ra) return (*fp = ret_addr);
        return NULL;
    } else {
        return (my_ra);
    }
}

int main (int argc, char **argv) {
    void *ret_addr;
    int i = 0;

    ret_addr = frameloop(NULL);
    printf("Hello World %d\n", i++);
    if (i < 10) {
        frameloop(ret_addr);
    }
}

```

### Explanation:

* `main()` first calls `frameloop(NULL)`. In this case use the `__builtin_return_address()` builtin to get the return address (in `main()`) that `frameloop()` will return to. We return this address.
* `printf()` to show we're looping
* now we call `frameloop()` with the return address for the previous call. We look through the stack for the current return address, and when we find it, we substitute the previous return address.
* We then return from the 2nd `frameloop()` call. But since the return address was hacked above, we end up returning to the point in `main()` where the first call should return to. Thus we end up in a loop.

The search for the return address in the stack would of course be cleaner as a loop, but I unrolled a few iterations for the sake of no looping whatsoever.

### Output:

```
$ CFLAGS=-g make frameloop
cc -g    frameloop.c   -o frameloop
$ ./frameloop
Hello World 0
Hello World 1
Hello World 2
Hello World 3
Hello World 4
Hello World 5
Hello World 6
Hello World 7
Hello World 8
Hello World 9
$

```

# Answer
> 27 votes
# Haskell

The following code contains **no recursive function (even indirectly), no looping primitive and doesn't call any built-in recursive function** (uses only `IO`'s output and binding), yet it repeats a given action idenfinitely:

```
data Strange a = C (Strange a -> a)

-- Extract a value out of 'Strange'
extract :: Strange a -> a
extract (x@(C x')) = x' x

-- The Y combinator, which allows to express arbitrary recursion
yc :: (a -> a) -> a
yc f =  let fxx = C (\x -> f (extract x))
        in extract fxx

main = yc (putStrLn "Hello world" >>)

```

Function `extract` doesn't call anything, `yc` calls just `extract` and `main` calls just `yc` and `putStrLn` and `>>`, which aren't recursive.

**Explanation:** The trick is in the recursive data type `Strange`. It is a recursive data type that consumes itself, which, as shown in the example, allows arbitrary repetition. First, we can construct `extract x`, which essentially expresses self-application `x x` in the untyped lambda calculus. And this allows to construct the Y combinator defined as `λf.(λx.f(xx))(λx.f(xx))`.

---

**Update:** As suggested, I'm posting a variant that is closer to the definition of **Y** in the untyped lambda calculus:

```
data Strange a = C (Strange a -> a)

-- | Apply one term to another, removing the constructor.
(#) :: Strange a -> Strange a -> a
(C f) # x = f x
infixl 3 #

-- The Y combinator, which allows to express arbitrary recursion
yc :: (a -> a) -> a
yc f =  C (\x -> f (x # x)) # C (\x -> f (x # x))

main = yc (putStrLn "Hello world" >>)

```

# Answer
> 26 votes
## C++

The following outputs a countdown from 10 to "Blast off!" using template metaprogramming.

```
#include <iostream>

template<int N>
void countdown() {
    std::cout << "T minus " << N << std::endl;
    countdown<N-1>();
}

template<>
void countdown<0>() {
    std::cout << "Blast off!" << std::endl;
}

int main()
{
    countdown<10>();
    return 0;
}

```

It might look like a classic example of recursion, but it actually isn't, at least technically, depending on your definition. The compiler will generate ten *different* functions. `countdown<10>` prints "T minus 10" and then calls `countdown<9>`, and so on down to `countdown<0>`, which prints "Blast off!" and then returns. The recursion happens when you compile the code, but the executable doesn't contain any looping structures.

In C++11 one can achieve similar effects using the `constexpr` keyword, such as this factorial function. (It's not possible to implement the countdown example this way, since `constexpr` functions can't have side-effects, but I think it might be possible in the upcoming C++14.)

```
constexpr int factorial(int n)
{
    return n <= 1 ? 1 : (n * factorial(n-1));
}

```

Again this really looks like recursion, but the compiler will expand out `factorial(10)` into `10*9*8*7*6*5*4*3*2*1`, and then probably replace it with a constant value of `3628800`, so the executable will not contain any looping or recursive code.

# Answer
> 21 votes
## Java

Let's play with Java class loader and set it as its own parent:

```
import java.lang.reflect.Field;

public class Loop {
    public static void main(String[] args) throws Exception {
        System.out.println("Let's loop");
        Field field = ClassLoader.class.getDeclaredField("parent");
        field.setAccessible(true);
        field.set(Loop.class.getClassLoader(), Loop.class.getClassLoader());

    }
}

```

This loop is actually so strong you'll have to use a `kill -9` to stop it :-)

It uses 100,1% of my Mac's CPU.

You can try to move the `System.out` at the end of the main function to experiment an alternate funny behavior.

# Answer
> 20 votes
# CSharp

One more and equally wicked::

```
public class P{

    class A<B>{
        public static int C<T>(){
            System.Console.WriteLine(typeof(T));
            return C<A<T>>();
        }
    }
    public static void Main(){
        A<P>.C<int>();
    }
}

```

This is not recursion... this is reification of code templates. While it appears we are calling the same method, the runtime is constantly creating new methods. We use the type parameter of int, as this actually forces it to create an entire new type and each instance of the method has to jit a new method. It cannot code share here. Eventually, we kill the call stack as it waits infinitely for the return of int that we promised but never delivered. In a similar fashion, we keep writing the type we created to keep it interesting. Basically each C we call is an enitrely new method that just has the same body. This is not really possible in a language like C++ or D that do their templates at compile time. Since, C# JIT is super lazy it only creates this stuff at the last possible moment. Thus, this is another fun way to get csharp to keep calling the same code over and over and over...

# Answer
> 14 votes
## Dart

I guess this would be the classical way of doing recursion without any actual recursive function. No function below refers to itself by name, directly or indirectly.

(Try it at dartpad.dartlang.org)

```
// Strict fixpoint operator.
fix(f) => ((x)=>f(x(x))) ((x)=>(v)=>f(x(x))(v));
// Repeat action while it returns true.
void repeat(action) { fix((rep1) => (b) { if (b()) rep1(b); })(action); }

main() {
  int x = 0;
  repeat(() {
    print(++x);
    return x < 10;
  });
}

```

# Answer
> 14 votes
## Redcode 94 (Core War)

`MOV 0, 1`

Copies instruction at address zero to address one. Because in Core War all addresses are relative to current PC address and modulo the size of the core, this is an infinite loop in one, non-jump, instruction.

This program (warrior) is called "Imp" and was first published by AK Dewdney.

# Answer
> 12 votes
## JS

Not very original but small. 20 chars.

```
setInterval(alert,1)

```

# Answer
> 12 votes
# Signals in C

```
#include <stdio.h>
#include <signal.h>

int main(void) {
    signal(SIGSEGV, main);
    *(int*)printf("Hello, world!\n") = 0;
    return 0;
}

```

The behaviour of this program is obviously very much undefined, but today, on my computer, it keeps printing "Hello, world!".

# Answer
> 11 votes
# Emacs Lisp

This is a great time to show off Lisp's powerful design where "code is data and data is code". Granted, these examples are very inefficient and this should never be used in a real context.

The macros generate code that is an unrolled version of the supposed loop and that generated code is what is evaluated at runtime.

## repeat-it: allows you to loop N times

```
(defmacro repeat-it (n &rest body)
  "Evaluate BODY N number of times.
Returns the result of the last evaluation of the last expression in BODY."
  (declare (indent defun))
  (cons 'progn (make-list n (cons 'progn body))))

```

## repeat-it test:

```
;; repeat-it test
(progn
  (setq foobar 1)

  (repeat-it 10
    (setq foobar (1+ foobar)))

  ;; assert that we incremented foobar n times
  (assert (= foobar 11)))

```

## repeat-it-with-index:

This macro is like `repeat-it` but it actually works just like the common looping macro `do-times` it allows you to specify a symbol that will be bound to the loop index. It uses an expansion time symbol to ensure that the index variable is set correctly at the beginning of each loop regardless of whether or not you modify it's value during the loop body.

```
(defmacro repeat-it-with-index (var-and-n &rest body)
  "Evaluate BODY N number of times with VAR bound to successive integers from 0 inclusive to n exclusive..
VAR-AND-N should be in the form (VAR N).
Returns the result of the last evaluation of the last expression in BODY."
  (declare (indent defun))
  (let ((fallback-sym (make-symbol "fallback")))
    `(let ((,(first var-and-n) 0)
           (,fallback-sym 0))
       ,(cons 'progn
              (make-list (second var-and-n)
                         `(progn
                            (setq ,(first var-and-n) ,fallback-sym)
                            ,@body
                            (incf ,fallback-sym)))))))

```

## repeat-it-with-index test:

This test shows that:

1. The body does evaluate N times
2. the index variable is always set correctly at the beginning of each iteration
3. changing the value of a symbol named "fallback" won't mess with the index

```
;; repeat-it-with-index test
(progn
  ;; first expected index is 0
  (setq expected-index 0)

  ;; start repeating
  (repeat-it-with-index (index 50)
    ;; change the value of a  'fallback' symbol
    (setq fallback (random 10000))
    ;; assert that index is set correctly, and that the changes to
    ;; fallback has no affect on its value
    (assert (= index expected-index))
    ;; change the value of index
    (setq index (+ 100 (random 1000)))
    ;; assert that it has changed
    (assert (not (= index expected-index)))
    ;; increment the expected value
    (incf expected-index))

  ;; assert that the final expected value is n
  (assert (= expected-index 50)))

```

# Answer
> 11 votes
# Untyped lambda calculus

```
λf.(λx.f (x x)) (λx.f (x x))

```

# Answer
> 10 votes
**Haskell, 24 characters**

```
sequence_ (repeat (print "abc"))

```

or in a condensed form, with 24 characters

```
sequence_$repeat$print""

```

(although the text is changed, this will still loop - this will print two quotes and a newline infinitely)

explanation: print "abc" is basically an i/o action that just prints "abc".
repeat is a function which takes a value x and returns an infinite list made of only x.
sequence\_ is a function that takes a list of i/o actions and returns an i/o action that does all of the actions sequentially.

so, basically, this program makes an infinite list of print "abc" commands, and repeatedly executes them. with no loops or recursion.

# Answer
> 10 votes
## ASM (x86 + I/O for Linux)

It does not matter how much your puny high level languages will struggle, it will still be just hidden instruction pointer manipulation. In the end it will be some sort of "goto" (jmp), unless you are bored enough to unroll loop in runtime.

You can test code on Ideone

You can also check out more refined version of this idea in Matteo Italia DOS code.

It starts with string of 0..9 and replaces it with A..J, no direct jumps used (so lets say that no "goto" happened), no recurrence either.

Code probably could be smaller with some abuse of address calculation, but working on online compiler is bothersome so I will leave it as it is.

Core part:

```
mov dl, 'A' ; I refuse to explain this line!
mov ebx, msg ; output array (string)

call rawr   ; lets put address of "rawr" line on stack
rawr: pop eax ; and to variable with it! In same time we are breaking "ret"

add eax, 4 ; pop eax takes 4 bytes of memory, so for sake of stack lets skip it
mov [ebx], dl ; write letter
inc dl ; and proceed to next
inc ebx
cmp dl, 'J' ; if we are done, simulate return/break by leaving this dangerous area
jg print

push eax ; and now lets abuse "ret" by making "call" by hand
ret

```

Whole code

```
section     .text
global      _start

_start:

;<core>
mov dl, 'A'
mov ebx, msg

call rawr
rawr: pop eax

add eax, 4
mov [ebx], dl
inc dl
inc ebx
cmp dl, 'J'
jg print

push eax
ret
;</core>

; just some Console.Write()
print:
    mov     edx,len
    mov     ecx,msg
    mov     ebx,1
    mov     eax,4
    int     0x80

    mov     eax,1
    xor     ebx, ebx
    int     0x80

section     .data

msg     db  '0123456789',0xa
len     equ $ - msg

```

# Answer
> 9 votes
# C Preprocessor

A little "technique" that I came up with during an obfuscation challenge. There's no function recursion, but there is... file recursion?

noloop.c:

```
#if __INCLUDE_LEVEL__ == 0
int main()
{
    puts("There is no loop...");
#endif
#if __INCLUDE_LEVEL__ <= 16
    puts(".. but Im in ur loop!");
    #include "noloop.c"
#else
    return 0;
}
#endif

```

I wrote/tested this using gcc. Obviously your compiler needs to support the `__INCLUDE_LEVEL__` macro (or alternatively the `__COUNTER__` macro with some tweaking) in order for this to compile. It should be fairly obvious how this works, but for fun, run the preprocessor without compiling the code (use the `-E` flag with gcc).

# Answer
> 8 votes
# PHP

Here's one with PHP. Loops by including the same file until counter reaches $max:

```
<?php
if (!isset($i))
    $i = 0;        // Initialize $i with 0
$max = 10;         // Target value

// Loop body here
echo "Iteration $i <br>\n";

$i++;               // Increase $i by one on every iteration

if ($i == $max)
    die('done');    // When $i reaches $max, end the script
include(__FILE__);  // Proceed with the loop
?>

```

The same as a for-loop:

```
<?php
for ($i = 0; $i < 10; $i++) {
    echo "Iteration $i <br>\n";
}
die('done');
?>

```

# Answer
> 8 votes
# Python

The following code contains **no recursive function (directly or indirect), no looping primitive and doesn't call any built-in function** (except `print`):

```
def z(f):
    g = lambda x: lambda w: f(lambda v: (x(x))(v), w)
    return g(g)

if __name__ == "__main__":
    def msg(rec, n):
        if (n > 0):
            print "Hello world!"
            rec(n - 1)
    z(msg)(7)

```

Prints "Hello world!" a given number of times.

**Explanation:** Function `z` implements the strict **Z** fixed-point combinator, which (while not recursively defined) allows to express any recursive algorithm.

# Answer
> 8 votes
# Perl-regex

```
(q x x x 10) =~ /(?{ print "hello\n" })(?!)/;

```

demo

or try it as:

```
perl -e '(q x x x 10) =~ /(?{ print "hello\n" })(?!)/;'

```

The `(?!)` never match. So the regex engine tries to match each *zero width positions* in the matched string.

The `(q x x x 10)` is the same as `(" " x 10)` \- repeat the `space` ten times.

Edit: changed the "characters" to *zero width positions* to be more precise for better understandability. See answers to this stackoverflow question.

# Answer
> 8 votes
# z80 machine code

In an environment where you can execute at every address and map ROM everywhere, map 64kb of ROM filled with zeroes to the entire address space.

What it does: nothing. Repeatedly.

How it works: the processor will start executing, the byte `00` is a `nop` instruction, so it will just continue on, reach the address `$ffff`, wrap around to `$0000`, and continue executing `nop`s until you reset it.

To make it do slightly more interesting, fill the memory with some other value (be careful to avoid control flow instructions).

# Answer
> 6 votes
# T-SQL -12

```
print 1
GO 9

```

> Actually more of a quirk of Sql Server Management Studio. GO is a script separator and is not part of the T-SQL language. If you specify GO followed by a number it will execute the block that many times.

# Answer
> 6 votes
## C#

Prints out all integers from uint.MaxValue to 0.

```
   class Program
   {
      public static void Main()
      {
          uint max = uint.MaxValue;
          SuperWriteLine(ref max);
          Console.WriteLine(0);
      }

      static void SuperWriteLine(ref uint num)
      {
          if ((num & (1 << 31)) > 0) { WriteLine32(ref num); }
          if ((num & (1 << 30)) > 0) { WriteLine31(ref num); }
          if ((num & (1 << 29)) > 0) { WriteLine30(ref num); }
          if ((num & (1 << 28)) > 0) { WriteLine29(ref num); }
          if ((num & (1 << 27)) > 0) { WriteLine28(ref num); }
          if ((num & (1 << 26)) > 0) { WriteLine27(ref num); }
          if ((num & (1 << 25)) > 0) { WriteLine26(ref num); }
          if ((num & (1 << 24)) > 0) { WriteLine25(ref num); }
          if ((num & (1 << 23)) > 0) { WriteLine24(ref num); }
          if ((num & (1 << 22)) > 0) { WriteLine23(ref num); }
          if ((num & (1 << 21)) > 0) { WriteLine22(ref num); }
          if ((num & (1 << 20)) > 0) { WriteLine21(ref num); }
          if ((num & (1 << 19)) > 0) { WriteLine20(ref num); }
          if ((num & (1 << 18)) > 0) { WriteLine19(ref num); }
          if ((num & (1 << 17)) > 0) { WriteLine18(ref num); }
          if ((num & (1 << 16)) > 0) { WriteLine17(ref num); }
          if ((num & (1 << 15)) > 0) { WriteLine16(ref num); }
          if ((num & (1 << 14)) > 0) { WriteLine15(ref num); }
          if ((num & (1 << 13)) > 0) { WriteLine14(ref num); }
          if ((num & (1 << 12)) > 0) { WriteLine13(ref num); }
          if ((num & (1 << 11)) > 0) { WriteLine12(ref num); }
          if ((num & (1 << 10)) > 0) { WriteLine11(ref num); }
          if ((num & (1 << 9)) > 0) { WriteLine10(ref num); }
          if ((num & (1 << 8)) > 0) { WriteLine09(ref num); }
          if ((num & (1 << 7)) > 0) { WriteLine08(ref num); }
          if ((num & (1 << 6)) > 0) { WriteLine07(ref num); }
          if ((num & (1 << 5)) > 0) { WriteLine06(ref num); }
          if ((num & (1 << 4)) > 0) { WriteLine05(ref num); }
          if ((num & (1 << 3)) > 0) { WriteLine04(ref num); }
          if ((num & (1 << 2)) > 0) { WriteLine03(ref num); }
          if ((num & (1 <<  1)) > 0) { WriteLine02(ref num); }
          if ((num & (1 <<  0)) > 0) { WriteLine01(ref num); }
      }

      private static void WriteLine32(ref uint num) { WriteLine31(ref num); WriteLine31(ref num); }
      private static void WriteLine31(ref uint num) { WriteLine30(ref num); WriteLine30(ref num); }
      private static void WriteLine30(ref uint num) { WriteLine29(ref num); WriteLine29(ref num); }
      private static void WriteLine29(ref uint num) { WriteLine28(ref num); WriteLine28(ref num); }
      private static void WriteLine28(ref uint num) { WriteLine27(ref num); WriteLine27(ref num); }
      private static void WriteLine27(ref uint num) { WriteLine26(ref num); WriteLine26(ref num); }
      private static void WriteLine26(ref uint num) { WriteLine25(ref num); WriteLine25(ref num); }
      private static void WriteLine25(ref uint num) { WriteLine24(ref num); WriteLine24(ref num); }
      private static void WriteLine24(ref uint num) { WriteLine23(ref num); WriteLine23(ref num); }
      private static void WriteLine23(ref uint num) { WriteLine22(ref num); WriteLine22(ref num); }
      private static void WriteLine22(ref uint num) { WriteLine21(ref num); WriteLine21(ref num); }
      private static void WriteLine21(ref uint num) { WriteLine20(ref num); WriteLine20(ref num); }
      private static void WriteLine20(ref uint num) { WriteLine19(ref num); WriteLine19(ref num); }
      private static void WriteLine19(ref uint num) { WriteLine18(ref num); WriteLine18(ref num); }
      private static void WriteLine18(ref uint num) { WriteLine17(ref num); WriteLine17(ref num); }
      private static void WriteLine17(ref uint num) { WriteLine16(ref num); WriteLine16(ref num); }
      private static void WriteLine16(ref uint num) { WriteLine15(ref num); WriteLine15(ref num); }
      private static void WriteLine15(ref uint num) { WriteLine14(ref num); WriteLine14(ref num); }
      private static void WriteLine14(ref uint num) { WriteLine13(ref num); WriteLine13(ref num); }
      private static void WriteLine13(ref uint num) { WriteLine12(ref num); WriteLine12(ref num); }
      private static void WriteLine12(ref uint num) { WriteLine11(ref num); WriteLine11(ref num); }
      private static void WriteLine11(ref uint num) { WriteLine10(ref num); WriteLine10(ref num); }
      private static void WriteLine10(ref uint num) { WriteLine09(ref num); WriteLine09(ref num); }
      private static void WriteLine09(ref uint num) { WriteLine08(ref num); WriteLine08(ref num); }
      private static void WriteLine08(ref uint num) { WriteLine07(ref num); WriteLine07(ref num); }
      private static void WriteLine07(ref uint num) { WriteLine06(ref num); WriteLine06(ref num); }
      private static void WriteLine06(ref uint num) { WriteLine05(ref num); WriteLine05(ref num); }
      private static void WriteLine05(ref uint num) { WriteLine04(ref num); WriteLine04(ref num); }
      private static void WriteLine04(ref uint num) { WriteLine03(ref num); WriteLine03(ref num); }
      private static void WriteLine03(ref uint num) { WriteLine02(ref num); WriteLine02(ref num); }
      private static void WriteLine02(ref uint num) { WriteLine01(ref num); WriteLine01(ref num); }
      private static void WriteLine01(ref uint num) { Console.WriteLine(num--); }
   }

```

# Answer
> 6 votes
# JS (in browser)

How about this?

```
document.write(new Date());
location = location;

```

Prints the current time and reloads the page.

# Answer
> 5 votes
# 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;
}

```

# Answer
> 4 votes
# 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.

# Answer
> 4 votes
# 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.*

# Answer
> 3 votes
# 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);}

```

# Answer
> 3 votes
# 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).

# Answer
> 3 votes
## 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.

# Answer
> 3 votes
# 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>

```

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
## 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)

```

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
**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.

# Answer
> 3 votes
# 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

```

# Answer
> 3 votes
# 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.

# Answer
> 2 votes
**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

# Answer
> 2 votes
## 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.

# Answer
> 2 votes
# 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...

# Answer
> 2 votes
## 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');
});

```

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
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,

# Answer
> 2 votes
**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 );

```

# Answer
> 2 votes
# 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
...

```

# Answer
> 2 votes
**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.

# Answer
> 2 votes
# 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!`.

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!

# Answer
> 2 votes
**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

```

# Answer
> 2 votes
# 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`.

# Answer
> 2 votes
**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".

# Answer
> 2 votes
## 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;
}

```

# Answer
> 1 votes
# Perl

```
$b = ($i = <>) - ~-$i;
{
    ($b, $a) = ($a + $b, $b);
    redo if --$i
}
print "$a\n";

```

This takes an input from STDIN and prints the n-th Fibonacci number.

`($i = <>)` initializes `$i` with the input. Then `$b` is set to `1` by a bit of bit manipulation and subtraction. The "magic" here is done by the `redo` operator. It makes it possible to reevaluate the same block, without the need of loop. The calculation of `$a` and `$b` is redone until the subtraction of one by `$i` evaluates to `False` i.e. `0`. I think that the `print` statement in the end is self-explanatory.

Here's one more solution using `map` instead of `redo`:

```
print ~~ (
    map {
        ($b, $a) = ($a + $b, $b)
    } ++$b .. <>
)[-1] . $/;

```

This generates an array of up to the requested number of the Fibonacci sequence and prints the last entry. `++$b` initializes `$b` to `1`. Then the end of the rage, generated by `..`, is read by `<>`. `map` iterates it and the calculation is returned as an array. Then `[-1]` uses the last element to print.

# Answer
> 1 votes
# C#

Since we can't loop... why don't we use events instead?

```
static void Main(string[] args)
{
    var timer = new Timer(1000);
    timer.Elapsed += (o,e) => Console.WriteLine("Cheese!");
    timer.Start();
    Console.ReadLine();
}

```

# Answer
> 1 votes
This is pretty cheap I guess.

I think semanatically, you can argue that the constructor isn't directly calling itself.

## Python

```
class MyClass:
    i = 0
    subClass = None
    def __init__(self, i):
        self.i = i
        if i != 5:
            self.subClass = MyClass(i+1)
        print self.i

c = MyClass(1)

```

# Answer
> 1 votes
Visual Basic 6.0

```
Public Function TimerOn(Interval As Integer)
    If Interval > 0 Then
        ' Start the timer.
        Timer1.Interval = Interval
    Else
        ' Stop the timer.
        Timer1.Interval = 0
    End If
End Function

```

# Answer
> 1 votes
# Python

Pretty similar to @dwjohnston's answer.

```
class z:v=c
g=z()
def f():z.v-=1;y();return z.v!=0
class x:__eq__=lambda s,x:s==x if f()else 1
x()==0

```

Assumes that `y` is the function you want to call `c` times (set c to a negative number for infinite, though it hits the recursion depth limit pretty quickly)

# Answer
> 1 votes
# Emacs Lisp

Jordon Biondo already mentioned this, but here is a very minimalistic version of the macro based loop. It uses the backquote and comma syntax to save some `eval`s:

```
(defmacro macroloop (s n)
  (if (> (eval n) 0)
      (progn
        (macroexpand `(macroloop ,s ,(- n 1)) )
        (print s)
        )
    )
  )

(macroloop "hello world" 10)

```

# Answer
> 1 votes
SQL (oracle 10g or above)

```
select level from dual connect by 1=1;

```

This will generate rows from 1 to infinite.

# Answer
> 1 votes
# php

Very simple method, this happens every once in a while when not paying attention:

```
header('Location: thisPage.php');

```

# Answer
> 1 votes
# JavaScript

Small loop when listening on DOM tree modification :

```
var int=0;
document.addEventListener('DOMNodeInserted', function(){
    int++;
    console.log('Loop ' + int);
    if(int < 5) document.body.appendChild(document.createElement('div'));
});
document.body.appendChild(document.createElement('div'));

```

It just add an element and retrigger the event.

# Answer
> 1 votes
```
Public Event e()

Public Function a() Handles Me.e

   RaiseEvent e()

End Function

a()

```

# Answer
> 1 votes
# C

This is a fork bomb. It is not a "function that calls itself" but instead is a "program that calls itself".

```
int main(int argc, char **argv)
{
    fork();
    printf("Hello world\n");
    return system(argv[0]);
}

```

# Answer
> 1 votes
## Java Swing

```
import java.awt.event.*;
import javax.swing.JButton;

public class Looper {
    public static void main(String[] args) {
        final JButton button = new JButton();
        new JButton().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                button.doClick();
            }
        });
        button.doClick();
    }
}

```

# Answer
> 1 votes
## Haskell

```
main=foldr1 (>>) $ repeat $ putStrLn "Yolo

```

Repeatedly displays "Yolo".

Note: Folds and repeat are not structures, they are functions

Note: I did not specify which implementation of prelude I am using. Therefore, the above functions do not necessarily use recursion. The haskell standard specifically says that any implementation of `foldr1` and `repeat` with the same semantics as the above are valid, even without recursion.

# Answer
> 1 votes
# C# threaded solution

You'll need to turn off catching for the DangerousThreadingAPI exception for this to work correctly without stopping. make sure to include the System.Threading library with a using statement at the start of the program

```
    int mycounter = 0;
        Thread themainthread = Thread.CurrentThread;
        System.Action<object> thethreadworkoriginal= new System.Action<object>((actionobject) =>
        {

            System.Action<object> theotheraction = (System.Action<object>)actionobject;
            Console.WriteLine(mycounter);
            mycounter++;
            if (mycounter == 10)
            {
                themainthread.Resume();
                return;

            }
            ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(theotheraction), theotheraction);

        });

        System.Action<object> thethreadworknew = new System.Action<object>((actionobject) =>
     {

         System.Action<object> theotheraction = (System.Action<object>)actionobject;

         ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(thethreadworkoriginal),thethreadworkoriginal);
     });

        Thread thestartingthread = new Thread(new ParameterizedThreadStart(thethreadworknew));
        thestartingthread.Start(thethreadworkoriginal);
        //let the "loop" finish
        themainthread.Suspend();
        Console.WriteLine(mycounter);

```

# Answer
> 1 votes
## JavaScript with HTML

If you put this tag into a page, your hit-counter will soar! (In the short term anyway.)

```
<script>
    var oldLocation = window.location;

    window.location = 'middle.nowhere';

    window.location = oldLocation;

    alert('You shouldn\'t have tried this.');
</script>

```

Yet another browser breaker. Shockingly easy. It's safe to run the code once, but don't put the tag on a page and try to load it unless you're done browsing for a while.

**Edit**: I missed it in my prior searching, but Pichan beat me to posting this concept. My answer explains how to use this code and includes handling for an extra edge-case, so I'm leaving it up until I'm led to believe that this is bad etiquette.

# Answer
> 1 votes
## Scala

```
def while_(cond: => Boolean)(f: => Unit): Unit = Stream.continually(f).find(_ => !cond)

```

Example usage:

```
var i = 1
while_(i <= 100) {
  println(i)
  i = i + 1
}

```

Prints out 1 through 100, in order.

# Answer
> 1 votes
# Rebol

```
loopy: function [times block] [
    loop: copy []
    append/dup loop block times
    do loop
]

```

Usage example in Rebol console:

```
>> loopy 3 [print "hello world!"]
hello world!
hello world!
hello world!

```

The `loopy` function takes a `block` of code and simply duplicates itself the necessary number of `times` into a series (array) called `loop` (see `append/dup loop block times`). Then it just evals that `loop` series with `do loop`.

So if you could see the `loop` series within the above example it would look like this:

```
[print "hello world!" print "hello world!" print "hello world!"]

```

So code being data then this is what happens:

```
>> do [print "hello world!" print "hello world!" print "hello world!"]
hello world!
hello world!
hello world!

```

# Answer
> 1 votes
## JavaScript

```
code = 'alert(\' Lorem Ipsum \');';
num = 5;
eval(new Array( num + 1 ).join( code ));

```

`num` is the number of times to repeat the code in the string `code`. This repeats the String `code` the number of times in `num` and executes it with `eval`.

# Answer
> 1 votes
## JavaScript

**Warning**: This may kill your browser.

```
(function(){
    arguments.callee.call(this);
})();

```

What happens here is, we've used the SEAF or Self Executing Anonymous Function to execute a function that will simply call it's callee again (so technically no recursion as the method is not calling itself :) ). The callee is again the SEAF and as such executing this will result in:

> Uncaught RangeError: Maximum call stack size exceeded

# Answer
> 1 votes
## Javascript

```
<script>
    var button = document.createElement('button');
    button.addEventListener('click', document.createElement);
    window.onerror = setTimeout.bind(window, button.click);
    button.click();
</script>

```

**Explanation:** document.createElement() expects a parameter, so clicking the button causes an error to be thrown. The window catches the error and dispatches another click to the button. I don't think this meets the definition of recursion provided since the browser's event loop is invoking the error handler.

# Answer
> 1 votes
# JavaScript

```
eval(Array(9).join("alert('loopy');"));

```

# Answer
> 1 votes
## ZX Spectrum Basic

```
10 PRINT "Hello"
20 POKE 23618,10:POKE 23619,0:POKE 23620,1

```

This uses the system variables to execute a goto.
The first 2 **POKE**s specify the line number
The last **POKE** specifies which statement on that line, and causes the goto to execute

# Answer
> 1 votes
# J

Some bit twiddling in J

```
-^:_] 1

```

Broken down:

* `-` : change sign of input
* `^:` power conjunction. With right argument _ (infinity): return a verb which does do the left argument till convergence (in this case: forever)
* 1 : argument to the derived verb

This effectively keeps changing the sign of one till you break the process.

# Answer
> 1 votes
## Tcl

```
# I'd like to call "if" "when" instead.
rename if when
when 0 do stuff

```

> if expresion then else - will execute `stuff`
> `stuff` is not defined, so `unknown` is called, which uses `if`, which does not exist - calling `unknown`

# Answer
> 1 votes
# Unlambda

```
``cc`cc

```

Loops infinitely. ("Verify" it here.) Abuse of the language's call with current continuation primitive `c`.

# Answer
> 1 votes
# \>\<\>

This code uses the fact the \>\<\> (fish) wraps around to execute the trampoline instruction repeatedly, jumping over itself like a lonely leap-frog.

```
!

```

# Answer
> 1 votes
# Java

```
new Timer().schedule(new TimerTask() {
    public void run() {
        System.out.println("Loop without Looping");
    }
}, 0, 1);

```

# Answer
> 1 votes
# 68k Assembly

This will only work if the code is stored in writable memory. It's low-level enough that it might work differently on different platforms, but it's verified to work on the EASy68k simulator.

```
    ORG $1000
START:
    ; Set value that counter will count down from
    MOVE #5,D1

    ; call counter (and as a side-effect, store the current value
    ; of the program counter + 4 on the stack so it will still work even
    ; if the code is loaded somewhere other than 0x1000)
    JSR counter

    ; Exit program
    MOVE.B #9,D0
    TRAP #15

counter:
    ; Modify the value of the ADDQ instruction in-memory so it does a
    ; conditional branch instead of undoing the subtraction
    MOVE.L (SP),A0
    ADD.W #$1af5,22(A0)

    ; print value in D1 as integer
    MOVE.B #3,D0
    TRAP #15

    ; D1 = D1 - 1 + 1
    SUBQ.B #1,D1
    ADDQ.B #1,D1

    ; return
    RTS

    END START

```

# Answer
> 1 votes
**JAVA**

I'm so surprise nobody used non-static initializer block yet.

```
public class Pear {

    {
        System.out.println("Hello non-static initializer");
        new Pear();
    }

    public static void main(String[] args) throws IOException {
    new Pear();
    }
}

```

This will print out `"Hello non-static initializer"` till it will throw StackOverflow error

# Answer
> 0 votes
# Python 2.7

I presume building a list isn't technically looping. Because if so, this works

```
def forLoop(x):
  print "hello"

map(forLoop, range(0,5))

```

gives:

```
0 hello
1 hello
2 hello
3 hello
4 hello

```

# Answer
> 0 votes
# BASH

```
cat /dev/random

```

It repeatedly prints `random` to the screen without using any repetition. Simple as that. Theoretically you can use any input device.

# Answer
> 0 votes
# PHP

This one's kind of borderline recursive. The code calls itself through eval().

```
$max = 10;
$i = 0;

$e = <<<'EOS'
    echo "Spudro spärde $i<br>";

    $i++;
    if ($i < $max)
        eval($e);
EOS;

eval($e);

```

# Answer
> 0 votes
Call this codgolf0.py, run with `python codegolf0.py 0`

```
from subprocess import call
import sys
import os

i = int(sys.argv[1])
print i
call( "copy /y codegolf"+str(i)+  ".py codegolf"+str(i+1)+".py >nul ", shell=True)

if i<10:
    call("python codegolf"+str(i+1)+".py "+ str(i+1), shell=True)

```

Admittedly, copying the .py isn't necessary, could just use repeated system calls to the python. The way I got to this was by getting the python to manually write the new python script, before I realised I was chasing my tail.

# Answer
> 0 votes
# Java

Looping without loops? Why not just use a Timer?

```
import java.util.Timer;
import java.util.TimerTask;

public class TimerLoop {
    private static class LoopTask extends TimerTask {
        private int count = 99;
        private final Timer timer;

        public LoopTask(Timer timer) {
            this.timer = timer;
        }

        @Override
        public void run() {
            --count;
            if (count < 0) {
                timer.cancel();
                return;
            }
            System.out.println(count + " bottle(s) of beer on the wall...");
        }
    }

    public static void main(String[] args) {
        Timer t = new Timer();
        t.schedule(new LoopTask(t), 0, 100);
    }
}

```

# Answer
> 0 votes
## R

I am not sure if this is allowed.

```
lapply(letters, print)

```
1. The first argument is a vector (list) - letters in this case.
2. The second argument is a function to be applied on each element of the first argument.
3. The output is a list of values - the result of the function.

# Answer
> 0 votes
# Bash

```
coproc a { bash; }
echo "x='echo \$x;echo y >&2'" >&${a[1]}
echo 'echo $x' >&${a[1]}
cat <&${a[0]} >&${a[1]}

```

It has the same output as `yes`, but to `stderr`.

# Answer
> 0 votes
```
<html>
<script>
function method()
{
    //do something
    location.reload();
}
</script>
<body onload="method()">
</body>
</html>

```

It keeps reloading the web page.

# Answer
> 0 votes
# **Golfscript, (24 + message)**

```
".{('All work and no play makes Jack a dull boy\n'print W~}{;}if":W~

```

Takes an integer 'n' off the stack and prints the given string n times.

Each iteration checks if there are more iterations to go, and if so, it prints the message and pushes a copy of the execution code onto the stack.

The code for each iteration is stored in the variable 'W'.

This method can be used as a work-around for the issue with nested 'while' loops in the online golfscript interpreter.

# Answer
> 0 votes
# REXX:

```
x = 1
say "Now" x; x=x+1; if x<5 then interpret SOURCELINE(2)
exit

```

### Output:

```
Now 1
Now 2
Now 3
Now 4

```

### Explanation:

* `SOURCELINE(n)` retrieves source line `n` as a string, usually for displaying lines that return exceptions.
* The `INTERPRET` instruction takes a string parameter and passes it to the REXX interpreter which executes the string as if it were part of the program wrapped in a simple `DO...END` block (which therefore keeps procedure variables in scope).

The `IF` test keeps the "loop" down to 4 executions.

# Answer
> 0 votes
# Common Lisp

I wrote a macro (not a function, so it isn't using recursion as defined).

```
(defmacro myloop (num &body body)
  (if (= num 1)
    `(progn ,@body)
    `(progn ,@body (myloop ,(- num 1) ,@body))))

```

To execute `(myfunc arg)` `4` times, just

```
(myloop 4 (myfunc arg))

```

This will generate code that looks like:

```
(progn
  (myfunc arg)
  (progn
    (myfunc arg)
    (progn
      (myfunc arg)
      (progn
        (myfunc arg)))))

```

# Answer
> 0 votes
# **D**

Using templates and string mixins.

```
import std.stdio;

void main() {
    mixin(MeinLoop!(`"You said a *function* couldn't call itself!"`, 100));
}

template MeinLoop(string message, int n) if(n > 0) {
    enum MeinLoop = "writeln(" ~ message ~ ");" ~ MeinLoop!(message, n - 1);
}

template MeinLoop(string message, int n) if(n <= 0) {
    enum MeinLoop = `writeln("Done!");`;
}

```

## Cleaner version:

```
import std.stdio;

void main() {
    mixin(MeinLoop!(`"You said a *function* couldn't call itself!"`, 100));
}

template MeinLoop(string message, int n) {
    static if(n <= 0) {
        enum MeinLoop = `writeln("Done!");`;
    } else {
        enum MeinLoop = "writeln(" ~ message ~ ");" ~ MeinLoop!(message, n - 1);
    }
}

```

This prints `message` `n` times before printing "Done!", and as templates and mixins are not functions, this seems to abide by the rules.

**How it works**:

> At compile time, `mixin` injects whatever string it is passed into the program as code. In our case, we handed it a template with evaluates to a string containing statement which prints `message` to stdout, and the template then recurses until `n` copies of the string are injected into the file. Since we were instructed to not use recursive *functions*, this is valid.

# Answer
> 0 votes
# Python

```
#!/usr/bin/env python
import os
import sys
class FakeLoop(object):
    def __init__(self):
        self.execl = os.execl
        self.path = sys.argv[0]
    def __del__(self):
        self.execl(self.path, '')
fakeloop = FakeLoop()
print 'loop'

```

It's like tail-recursion for processes!

# Answer
> 0 votes
MOS6502version

$FFD2 is the CHROUT Kernal call on Commodore 8bit computers and prints the char in .a to the current output device. Change the $FFD2 to the correct address of "Print char in .a" for use on other 6502 computers.

Called from BASIC using SYS5000, this prints the alphabet ABC...XYZ on a single line, then returns to the BASIC prompt.

```
*=$1386
.BYTE 0,0 ; char & count storage
ENTER=* ; use "SYS5000" from BASIC prompt to execute
    LDA #"A"-1    ; initial character to print is A
    STA  ENTER-2
    LDA #26       ; print 26 characters
    STA  ENTER-1
    LDA #>ENTER-1 ; high byte of addr-1
    PHA
    LDA #<ENTER-1 ; low byte of addr-1
    PHA
    DEC  ENTER-1  ; Countdown finished when -1
    BPL  PRT
    PLA           ; clean the stack
    PLA
    RTS           ; and return to caller
PRT=*
    INC  ENTER-2  ; update char to print
    LDA  ENTER-2  ; print the char and continue
    JMP  $FFD2    ; Actually a JSR, the return addr was put on stack earlier

```

Technically, this and the earlier x86 code use GoTo as the RTS/RET will goto the address on the stack when executed.

It works nicely to implement a case statement in 6502 :)

# Answer
> 0 votes
Well since people seem to like redcode:

```
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
MOV.I 1, {-1

```

Erases all of memory under standard configuration then dies.

# Answer
> 0 votes
# JavaScript (in an old-ish browser)

```
var el = document.createElement('input');
el.onfocus = function() {
  alert("ha");
};
document.body.appendChild(el);
el.focus();

```

In older browsers, the alert will cause the input to be temporarily unfocused; when you dismiss the alert, the input will be re-focused and trigger the event handler again. And so on until you get annoyed and kill the process.

Unfortunately, though I distinctly remember seeing this in the past, I wasn't able to get this to happen in any modern browser - looks like it was considered a bug and fixed some time ago. I accept any and all downvotes for the datedness of this technique.

# Answer
> 0 votes
**JAVA using reflection**

```
 public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Golf golf = new Golf();
        golf.notALoop();
    }

    static class Golf{
        public void notALoop() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
            System.out.println("Its not directly calling it self");
            Method method = this.getClass().getMethod("notALoop");
            method.invoke(this);
        }
        }

```

# Answer
> 0 votes
**JAVA using a new thread**

```
public class HelloRunnable implements Runnable {
    public void run() {
        System.out.println("to be honest I find this question, not particularly interesting");
        (new Thread(new HelloRunnable())).start();
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }
}

```

# Answer
> 0 votes
**Haskell**

```
let x = 0:x in x

```

In GHCI, it prints `[0,0,0,...`. It uses recursion, but no function calls itself.

# Answer
> 0 votes
**Bash**

Replicator.sh

```
#!/bin/bash
cat $0 > $1
# do stuff
sh $1 $0

```

Then call

```
[user@host ~]$ sh Replicator.sh Replicant.sh

```

But will it pass the Voight-Kampff test?

# Answer
> 0 votes
C# Linq

Prints all numbers 0 - 10 inclusive

```
Enumerable.Range(0,11).ToList().ForEach(Console.WriteLine);

```

# Answer
> 0 votes
# PowerShell

```
date
sleep 1
$this = $MyInvocation.MyCommand.Definition
&"$this"

```

This will print the current date, wait 1 second and then the program will call itself endlessly...

# Answer
> 0 votes
## SAS

```
data _null_;
  set input_ds;
  call execute(" /*Logic goes here*/ ");
run;

```

There's no explicit do-loop or recursion, but the result is that your logic is executed once for each row in the input dataset.

Not the most creative submission, as the data step is the most fundamental feature of SAS, but I think this is *technically* correct as the question is currently written - none of the statements used on its own allows repeated execution of code.

EDIT: updated to use call execute to allow for execution of more or less arbitrary logic, rather than just data step logic.

# Answer
> 0 votes
**PHP**

My first attempt was almost identical to @Pichan's code:

```
<?php
if(!isset($counter)){$counter=1;}
echo $counter;
$counter++;
if($counter > 10){die('That&#39s enough!');}
include(__FILE__);
?>

```

Then I came up with this, but it might be too close to recursion to count. You dedide:

```
<?php
$b=null;
$a=function($count){
  if($count > 100){return;}
  global $a; //ugly, I know!
  global $b;
  if($a){
    $b=$a; $a=null;
    echo $count.' ';
    $b(++$count);
  }else{
    $a=$b;
    $b=null;
    echo $count.' ';
    $a(++$count);
  }
};

$a(0);
?>

```

# Answer
> 0 votes
# PHP

```
<?php

class a{
    function __destruct(){
        echo new Exception, "\n";
        global $x;
        $x = new a;
    }
}

$x=new a;

```

It is not a recursion. The destructor only calls the constructor of class a. The destructor itself is called after the destruction of the previous object. **The stack always has the same size** on each call of the destructor.

A more useful example:

```
<?php

class a{
    var $i;
    function __construct($i){
        echo "$i\n";
        $this->i = $i;
    }
    function __destruct(){
        global $x;
        if($this->i < 100)
            $x = new a($this->i + 1);
    }
}

$x=new a(1);

```

Count from 1 to 100.

# Answer
> 0 votes
**C#**

`() => Console.Write(DateTime.Now)` is just an example that can be eternally repeated. Any other `Action` can be substituted.

*loops eternally.*

```
using System;
using System.Collections;
using System.Linq;

class Program
{
    static void Main()
    {
        new S(() => Console.Write(DateTime.Now)).OfType<Action>().All(
            a =>
                {
                    a.Invoke();
                    return true;
                });
    }
}

class S : IEnumerable
{
    private Action a;

    public S(Action b)
    {
        a = b;
    }

    public IEnumerator GetEnumerator()
    {
        return new L(a);
    }
}

class L : IEnumerator
{
    public L(Action a)
    {
        Current = a;
    }

    public object Current { get; set; }

    public bool MoveNext()
    {
        return true;
    }

    public void Reset()
    {
    }
}

```

# Answer
> 0 votes
# Java

```
import java.util.Arrays;

public class Main
{
    public static void main( String args[] )
    {
        StringBuilder sb = new StringBuilder(1024*1024*4);
        sb.append("x");
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        String s = sb.toString();
        char[] chars = s.toCharArray();
        String x = Arrays.toString( chars).replace(",", "\n");
        x = x.substring( 1, x.length()-1);
        System.out.println(x);
    }
}

```

Prints 4194304 lines of 'x'.

# Answer
> 0 votes
# C++

OK, so the task is to do something repeatedly, without using a loop. However, the task does not say *how often* this has to be done, just that it has to be done repeatedly. So I figure the following program follows all rules, by repeatedly outputting "Hello world":

```
#include <iostream>

int main()
{
  std::cout << "Hello world\n";
  std::cout << "Hello world\n";
  std::cout << "Hello world\n";
}

```

Indeed, we can go even shorter: Since the tasks allows to freely choose what the repeated action is, I can just choose the action to be *do nothing!* Therefore the following program should also qualify, doing nothing a billion times in a row (of course, doing nothing takes no time, so the program terminates immediately):

```
int main()
{
}

```

But then, I can also do an infinite hello world "loop", by writing a custom stream buffer:

```
#include <iostream>
#include <streambuf>
#include <cstring>

class helloworldbuf:
  public std::streambuf
{
public:
  helloworldbuf();
private:
  int_type underflow();

  static char greeting[];
  static char* const end;
};

char helloworldbuf::greeting[] = "Hello world\n";

char* const helloworldbuf::end =
  helloworldbuf::greeting+std::strlen(helloworldbuf::greeting);

helloworldbuf::helloworldbuf()
{
  setg(end, end, end);
}

std::streambuf::int_type helloworldbuf::underflow()
{
    if (gptr() < egptr())
        return traits_type::to_int_type(*gptr());

    setg(greeting, greeting, end);

    return traits_type::to_int_type(*gptr());
}

int main()
{
  helloworldbuf hellobuf;
  std::cout << &hellobuf;
}

```

# Answer
> 0 votes
# Fun With Ruby Exceptions

Essentially, what we do is recursively throw errors until we have what we want, because real loops are for the weak.

The setup code:

```
class Exception
    alias real_init initialize
    def initialize(*args)
        real_init *args
        if args[0].is_a?(String) && args[0][0] == "\x04"
            hash = Marshal.load(args[0])
            success = send(hash[:condition], hash[:start_position])

            unless success
                hash[:start_position] = send(hash[:next_iteration], hash[:start_position])
                raise Marshal.dump(hash)
            end
            raise hash[:start_position].to_s
        end
    end
end

```

Example 1:

```
def condition(x)
    x > 10
end
def next_iteration(y)
    y += 1
end

h = {condition: "condition", next_iteration: "next_iteration", start_position: 3}

begin
    raise Marshal.dump(h)
rescue Exception => e
    puts e
end

```

Example 2 with strings:

```
def condition(x)
    x == "lol"
end
def next_iteration(y)
    y.next
end

h = {condition: "condition", next_iteration: "next_iteration", start_position: "lob"}

begin
    raise Marshal.dump(h)
rescue Exception => e
    puts e
end

```

Make sure you don't get any errors in the `next_iteration` or `condition` methods, or you will be getting strange results.

# Answer
> 0 votes
# JavaScript

```
function foreach(arr, fn, a, i) {
  if (!Array.isArray(a)) {
    a=fn.toString().match(/\(.*?\)/)[0].match(/[^()\s,]+/g);
  }
  if (i >= arr.length) return;
  foreachDo(arr,fn,a,i|0);
}

function foreachDo(arr, fn, a, i) {

  var params = arr.slice(i,i+a.length);
  fn.apply(fn,arr.slice(i,i+a.length));
  i+=a.length;
  foreach(arr, fn, a, i);
}

var people = ["John", "Doe", "Denver", "Jane", "Doe", "Seattle", "Bob", "Doe", "Summerset"];

foreach(people, function(first, last, city) {

  console.log(first + ' ' + last + ', ' + city);

});

John Doe, Denver
Jane Doe, Seattle
Bob Doe, Summerset

```

# Answer
> 0 votes
# ///

/// is a minimalistic programming language. It has only two commands: "output character literal", and "replace the first occurrence of first string literal with second string literal in the remainder of the program, repeating until the first string literal does not appear in the program".

In both commands, a backslash denotes that the next character is taken literally. The replacement command is `/first literal/second literal/`, and the output command is any character besides `/`. So, for example, the program `/lo\\c\k/\ake/che\ese\\clo\ck` first replaces every occurrence of `lo\ck` with `ake` (the `\`s before the `k` and the `a` have no effect), resulting in `che\ese\\cake`. Then the program executes the printing commands `c`, `h`, `e`, `\e`, `s`, `e`, `\\`, `c`, `a`, `k`, and `e`, thereby printing `cheese\cake`.

Needless to say, writing useful programs in /// is very difficult. The only way for a program to loop (besides using an infinite substitution like in `/a/aa/a`) is for a part of the program to use substitutions to create a copy of itself later in the program. I've never figured out how to do this, but Ørjan Johansen has written a program which does this:

```
/|/<-\\\\>\\\\\\//QT/|/R|N|/Q|T|/|/<-|\|\>|/<-|\|\|\|\>|\|\|\|\|/|/<|\->|/|/C|T|/C|\T|/C|T|/|/*|\
|/I|\N|/|/I|\N|/**|\
|/|/Q|\T|/Q|T|/R|N//RN/QT//<-\\>/<-\\\\>\\\\//<\->///CT/*
//Q\T/QT/RN

```

How does this work? I'm not completely sure, but it's something like this.

The first replacement replaces `|` (which is just syntactic sugar) with `<-\\>\\\`. The second replacement replaces the string `QT` with a quoted version of the second half of the program. In the second replacement command itself, most characters are preceded by `<-\\>\\\`. The result is that in the string produced *by* the second replacement, most characters are preceded by `<-\>\`.

The third replacement looks like it replaces `RN` with `QT`. But `QT` has been replaced with a quoted version of the program, where most characters are preceded by `<-\>\`. So this replacement actually replaces `RN` with yet another quoted version of the second half of the program, in which most characters are preceded by `<->`.

In the fourth replacement, each occurrence of `<-\>` is restored back to `<-\\>\\`. (I can't see where `<-\>` actually occurs.) The fifth replacement deletes every occurrence of `<->`, resulting in the quoted version of the second half of the program being completely restored to an unquoted state. The sixth replacement replaces `CT` with `*`—somehow this results in the program containing an ever increasing number of asterisks. The seventh replacement seems to do the same thing as the second replacement.

Finally, following all seven replacements is the string `RN`, which is eventually replaced with a copy of the program, and everything starts over.

The end result is that the program outputs an infinite triangle of asterisks.

Details about all this can be found at the Esolang wiki page for ///.

# Answer
> 0 votes
# Shell

Let's not forget about the classic, only works in a script file:

```
#!/bin/sh
echo do something here
exec $0

```

Another one that also works on the command line, employing a signal handler recursively calling itself by unusual means:

```
trap 'echo "do something here"; kill -s USR1 $$' USR1; kill -s USR1 $$

```

A script file moving it's content into a new temporary file, sourcing itself and removing old temporary file:

```
#!/bin/sh
# Only remove tempfile previously created by ourselves
[ "$tempfile" -a -f "$tempfile" ] && rm -f "$tempfile"

echo 'do something here'

export tempfile=$(tempfile) || exit 1
cat "$0" >"$tempfile" || exit 1
. "$tempfile"

```

# Answer
> 0 votes
## JavaScript (ES6)

Small and smart.

```
+(a = {x:0,valueOf: ()=>(a.x++,+a)})

```

This code can be written like this:

```
a = {
    x: 0,
    valueOf: function() {
        a.x++;
        a.valueOf();
    }
}
a.valueOf();

```

`+(obj)` tries to cast `obj` to number. It starts with calling `obj.valueOf`... And in this case, calling `obj.valueOf` results in an infinite loop, throwing stack overflow error.

# Answer
> 0 votes
# Roblox Lua

More events.

```
local n=0
local m=Instance.new("Message",game.Workspace)

script.ChildAdded:connect(function(e)
    wait()
    local k
    k=e.AncestryChanged:connect(function()
        wait()
        k:disconnect()
        e.Parent=script
    end)
    m.Text="Hi! "..n
    n=n+1
    e.Parent=game.Workspace
end)
Instance.new("IntValue",script)

```

Creates an IntValue as a child of the current script and then uses events to endlessly move it back and forth between the script and the workspace while producing output via a Message instance.

# Answer
> 0 votes
## Java 8

```
Stream.iterate("Look @ me slurping ur cpu", i -> i).forEach(System.out::println);

```

Starts an infinite stream with a string, and each next element is the same as the previous: `i -> i`. The stream is consumed by printing each element to stdout.

# Answer
> 0 votes
## AutoIt

I golfed this (sue me :P). It just writes 0 to the console very, very slowly (and maxes out one CPU core along the way). Compile as `a.exe`.

```
Exit ConsoleWrite(0)+Run("a")

```

If you want to run this (and you probably shouldn't), use this to kill it:

```
While 1
    ProcessClose("a.exe")
Wend

```

# Answer
> 0 votes
# Standard C89, no extensions

```
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    jmp_buf b;
    int i = 0, j;

    if (argc > 1) i = atoi(argv[1]);
    if (i<=0) i = 10;

    j = setjmp(b);

    if (j<i) {
        printf("%d\n", j);
        longjmp(b, j+1);
    }
    return EXIT_SUCCESS;
}

```

Compiles cleanly with `gcc -std=c89 -g -Wall -Wextra -pedantic`.

# Answer
> 0 votes
# C 42 bytes (w/single char return)

```
#include<stdio.h>
main(){printf("%9x",0);}

```

In this case, the printf is looping and printing up to 9 spaces to pad my hex output number 0. It is *executing* code (printing a space unless the output is filled) and *looping* (8 times in this case) without the usual loops. Tested on https://www.codechef.com/ide

# Answer
> 0 votes
# Molecule (v5.5+)

```
"lol!"~`q`n

```

Molecule has an built-in reflections system that allows code to be rewritten at runtime.

Output lol!, set the source code to the same one, which from v5.5 basically forces the interpreter to start reading from the start again.

# Answer
> 0 votes
# Python 2

```
class K(object):
    def __del__(self):
        print "You cannot stop the power of deallocators!"
        K()

```

This code goes into an infinite loop printing `You cannot stop the power of deallocators`.

Note that this **does not work in Python 3**

# Answer
> 0 votes
## Javascript ( 159 bytes )

This program relies on setInterval from javascript to iterate through an Enumerator (iterator). Uses a library I wrote to create an enumerator, and prints the value to the console

```
var e = _.Range(0,10).GetEnumerator();var id = setInterval(function(){var next = e.Next();if(next.Done){clearInterval(id);return;}console.log(next.Value);},1);

```

# Answer
> -1 votes
## VB6

Create a Timer on a form, set the Timer interval to 500

```
    Private Sub Timer1_Timer()
        Print "This is the lamest entry..."
    End Sub

```

Although it will not show any more printing once the form is full, it will run until it is stopped.

# Answer
> -2 votes
# JavaScript

### Array.foreach(function(item1, item2, ..){})

```
Array.prototype.foreach = function(callback) {

  var arr = this;
  var length = arr.length;
  var i = 0;
  var step = callback.length;

  function loopNext() {
    if (i < length) {
      loopBody();
    }
  }

  function loopBody() {
    callback.apply(arr, arr.slice(i,i+step));
    loopIncr();
  }

  function loopIncr() {
    i+=step;
    loopNext();
  }

  loopNext();
}

function testForeach() {
  var days = ['sun','Sunday',
              'mon','Monday',
              'tue','Tuesday',
              'wed','Wednesday',
              'thu','Thursday',
              'fri','Friday',
              'sat','Saturday'];

  var output = "";

  days.foreach(function(abbr, full) {
    output += full + '(' + abbr + '=' + this.indexOf(abbr) + ')\n';
  });

  document.getElementById('output').innerHTML = output;
}

testForeach();
```

```
<pre id="output"></pre>
```

---
Tags: popularity-contest, restricted-source
---


title: Antiprime Champions

text:
# Question
Title: Antiprime Champions
Consider the following table for the function `d(n)`, which calculates the number of factors that `n` is divisible by without a remainder:

```
n    | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | ...
d(n) | 1 | 2 | 2 | 3 | 2 | 4 | 2 | 4 | 3 | 4  | 2  | 6  | ...

```

Going from left to right, it is possible to determine the "champion" of the current subsequence:

* The first champion in the sequence `[1]` is `n = 1` with `d(1) = 1`.
* The second champion in the next sequence, `[1, 2]` is `n = 2` with `d(2) = 2`.
* The sequence `[1, 2, 3]` has no new champions, because `d(3) = d(2) = 2`, and `2` earned the title first.
* The third champion appears the sequence `[1, 2, 3, 4]`: `d(4) = 3`, which is greater than the previous champion with `d(2) = 2`.
* The next champion is `6` in `[1, 2, 3, 4, 5, 6]` with `d(6) = 4`.
* The next champion is `12` with `d(12) = 6`.

The champions can be denoted in the table:

```
n    | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | ...
d(n) | 1 | 2 | 2 | 3 | 2 | 4 | 2 | 4 | 3 | 4  | 2  | 6  | ...
       x   x       x       x                         x

```

You task is the following: Write a program that given an integer `n`, print all champions in the range `[1, n]` (`n` inclusive). The output format does not matter (test cases below display array format). Standard code golf rules and scoring applies.

## Test cases

```
1 -> [1]
2 -> [1, 2]
3 -> [1, 2]
4 -> [1, 2, 4]
5 -> [1, 2, 4]
6 -> [1, 2, 4, 6]
7 -> [1, 2, 4, 6]
8 -> [1, 2, 4, 6]
9 -> [1, 2, 4, 6]
10 -> [1, 2, 4, 6]
11 -> [1, 2, 4, 6]
12 -> [1, 2, 4, 6, 12]
24 -> [1, 2, 4, 6, 12, 24]
36 -> [1, 2, 4, 6, 12, 24, 36]

```

Hint: The output should always be a prefix of the List of Highly Composite Numbers.

# Answer
> 3 votes
# Jelly, 10 bytes

```
0rÆDL€»\IT

```

Try it online!

# Answer
> 2 votes
## 05AB1E, ~~16~~ 15 bytes

```
0U>GNÑg©X›i®UN,

```

**Explanation**

```
0U               # initialize the record as 0
  >G             # for each number in 1 to N
    NÑg©         # get number of divisors
        X›i      # if number of divisors is a new record
           ®U    # save new record
             N,  # print the new record holder on a new line

```

Try it online

# Answer
> 1 votes
# MATL, ~~14~~ 13 bytes

```
0i:t!\~sY>hdf

```

**Try it online!**

### Explanation

```
0      % Push 0
i:     % Take input n. Push [1 2 ... n]
t!\    % 2D array of all combinations of modulo between elements of [1 2 ... n]
~s     % Sum of zeros of each column. Gives number of divisors for [1 2 ... n]
Y>     % Cumulative maximum
h      % Concatenate with 0
d      % Consecutive differences
f      % Indices of nonzero elements. Implicitly display

```

---
Tags: code-golf, sequence
---


# Question
Title: Output quater-imaginary base numbers in binary
Write a function or program that outputs Quater-imaginary base displayed as binary digits. The number base is 2*i*, where *i* is the square root of -1. See Complex Number for more details on *i*. Each digit position can go from 0 to 3 (quaternary), as each real and imaginary part is -4 times as large as the previous real and imaginary part. The quaternary digits in binary are as follows: `0: 00`, `1: 01`, `2: 10` & `3: 11`.

Breakdown of digit positions:

```
re   im       16 -8i  -4  2i   1 -0.5i, etc.
 4    0        1   0   3   0   0        (quaternary representation)
              01  00  11  00  00        (binary representation)

```

The number `100110000` is 1x16 + 3x-4 = 16 + -12 = 4.

```
re   im       16 -8i  -4  2i   1 -0.5i, etc.
 0    5        0   0   0   3   0   2    (quaternary representation)
              00  00  00  11  00 .10    (binary representation)

```

The number `1100.1` is 3x2*i* \+ 2x-0.5*i* = 6*i* \+ -*i* = 5*i*.

Your code will take a pair of numbers, which could be integer or floating point, and will output the complex number as a string of binary digits. The first number will be real, the second input number will be the imaginary value. A binary point must only be printed if there are non-zero number positions below 1 (i.e. if any of the positions for -0.5*i*, -0.25, 0.125*i*, etc. have a non-zero digit). Leading and trailing zeros are not allowed, except for a single zero digit immediately before the binary point if there are no other digits. The output must not start with a binary point (\*`00.1` \- wrong, `0.1` \- right, *`.1` \- wrong, *`0.10` \- wrong). You may assume that all input numbers will have finite binary representations.

Test numbers:

```
re   im            output
 0    0                 0
 1    0                 1
 2    0                10
 3    0                11
 4    0         100110000
-1    0             10011
-2    0             10010
-3    0             10001
 0    1               100.1
 0    2               100
 0    3              1000.1
 0    4              1000
 0   -1                 0.1
 0   -2           1001100
 0   -3           1001100.1
 3    4              1011
 4    3         100111000.1
 6   -9         101110010.1
-6    9       10011100110.1
-9   -6           1110111
 0.5 14.125   10011001101.001001

```

Note: The output of all integer values will end in `.1` if the imaginary part is odd.

Standard code-golf.

# Answer
## JavaScript (ES6), 340 bytes

```
f=x=>[0,...x.toString(16)].reverse().map(d=>s=d<'.'?s:d<`0`?d+s.slice(0,-1):`${(c=+`0x${d}`+(c>>4)+m^m)>>2&3}${c&3}`+s,c=s='.',m=x<0?3:12)&&s
g=(s,t,n=s.indexOf`.`,m=t.indexOf`.`)=>n<m?g(0+s,t):n>m?g(s,0+t):t[s.length]?g(s+0,t):s.replace(/\d/g,(c,i)=>`${t[i]>>1}${t[i]&1}${c>>1}${c&1}`).replace(/^0+(\d)|\.?0*$/g,'$1')
(r,i)=>g(f(r),f(i/2))

```

`f` converts a number into base `-4` (with trailing `.` if the number is an integer). `g` takes two base `-4` numbers, pads them at both ends to the same length and `.` position, shuffles the digits together, converts everything from base `4` to base `2`, then finally strips leading and trailing zeros.

Explanation: To represent the given complex number in modified-base `2i` we need to represent the real part and half of the complex part (i.e. dividing the imaginary part by `2i`) in base `2i²` (i.e. `-4`), shuffle the digits together, and then convert them from base `4` to base `2`. To represent a real number in base `-4` we start with the base `4` conversion. Alternate digits have the correct sign (in the case of a positive number, these are the digits in the even positions; in the case of a negative number, these are the digits in the odd positions) but the remaining digits have the wrong sign and a correction needs to be applied. Examples:

```
 0 -> 000 -> 000 (no correction needed)
 4 -> 010 -> 130 }
 8 -> 020 -> 120 } (correction includes carry)
12 -> 030 -> 110 }

```

As you can see, the correction is `8` minus the original digit, mod `8`. However a slightly more convenient calculation is the original digit, plus 3, xor 3 (indeed in 32-bit integer arithmetic we could simply write `+0xCCCCCCCC^0xCCCCCCCC` to convert the entire number in one go). Finally as the correction applies to alternate digits it is simpler to do an initial conversion to base `16` which automatically picks up pairs of base `4` digits, then correct using a factor of either `3` or `0xC` as appropriate. It just remains to ignore the `-` sign.
> 2 votes

# Answer
## Perl - 313 bytes

Since no-one has posted an answer yet I thought I'd kick it off myself.

```
$r=$ARGV[0];$i=$ARGV[1]/2;$m=1;while($r!=int($r)||$i!=int($i)){$c++;$m*=-1;$i*=4;$r*=4}while($r||$i){$r-=($d[$n++]=$r/$m%4)*$m;$i-=($d[$n++]=$i/$m%4)*$m;$m*=-4}$_=join("",map({sprintf"%02b",$_}reverse splice(@d,$c*2)))||"0";@d and$_.=".".join("",map({sprintf"%02b",$_}reverse@d));s/^0+1/1/;s/(\.\d*1)0+$/$1/;print

```

I'm sure there are lots of opportunities to golf this further.
> 0 votes

---
Tags: code-golf, complex-numbers
---


title: Line numbering - implement nl

text:
# Question
Title: Line numbering - implement nl
Your task is to implement a program similar to the `nl` command-line tool from the GNU core utilities.

Standard loopholes are banned.

You may not use any built-in or external function, program or utility for numbering the lines of a file or string, such as `nl` itself or the `=` command in GNU sed.

# Specification

## Input

The program accepts filenames as arguments. Your code does not have to be cross-platform; the filename format of the OS running the code should be used, i.e. if you happen to be on Windows, the directory separator can be `\` or `/`.

You must be able to take 64 input files, including `-` if it is specified. If over 64 are given, only handle the first 64.

In the list of filenames, `-` represents standard input.

If filenames are given, read from the files in the order that they are given and concatenate their contents, inserting a new line between each one and at the end. If you cannot read from one or more of the filenames (because the file does not exist or you do not have read permissions for it), ignore them. If all filenames specified are invalid, output nothing.

If no filenames are given, read from standard input. Only read from standard input if no filenames are given or if `-` is given.

## Output

The program will output, to standard output, the input with lines numbered thus (You may assume that the input has `\n`, `\r\n` or `\r` line endings; pick whichever is convenient for you, but specify which one):

```
<5 spaces>1<tab><content of line 1 of input>
<5 spaces>2<tab><content of line 2 of input>
...
<4 spaces>10<tab><content of line 10 of input>
...
<3 spaces>100<tab><content of line 100 of input>
...
...

```

6 characters of space are allocated for the line number, and it is inserted at the end of these characters; the rest become spaces (e.g. `1` will have 5 leading spaces, `22` will have 4 leading spaces, ...). If the input is sufficiently long, you will eventually run out of space for the line number, at line `999999`. You must not output anything after line 999999.

If the input is empty, output nothing.

## Exit status

The lower numbers take priority: if errors 1 and 2 were encountered, exit with status 1.

Exit with status 0 if the input was successfully received, and the lines successfully numbered and output.

Exit with status 1 if one or more of the files specified on the command line were not found or could not be read from.

Exit with status 2 if too many files (more than 64) were given.

Exit with status 3 if the input was too long (more than 999999 lines).\

## Scoring

This is code-golf - shortest program wins!

I may add bonuses later for implementing certain options that `nl` has. There are no bonuses at the moment.

# Answer
## Bash, 121

```
s=$[2*($#>64)]
for f in "$@";{ [ -f $f ]||s=1;}
((s))&&exit $s
awk '{if(NR>=10**6){exit 3}printf("%6d\t%s\n",NR,$0)}' $@

```
> 6 votes

# Answer
# Ruby, 195

```
o,l=$*[64]?[2]:[],999999
($*==[]?[?-]:$*).each{|n|f=n==?-?STDIN: open(n)rescue o<<1&&next
s=f.read.lines
s[l]?o<<3:1
puts s[0..l].map.with_index(1){|l,i|i.to_s.rjust(6)+?\t+l}}
exit !o[0]?0:o.min

```
> 2 votes

# Answer
### python 173

```
import os,sys
c=0
l=1
for f in sys.argv[1:]:
    if c>64:exit(2)
    if not os.path.isfile(f):exit(1)
    c+=1
    for x in open(f):
        if l>=10**6:exit(3)
        print '%6d\t%s'%(l,x),;l+=1

```
> 1 votes

# Answer
## J (162)

```
exit(((2*64<#)[exit@3:`(stdout@(,&LF)@;@(,&TAB@(6&":)&.>@>:@i.@#,&.>]))@.(1e6>#)@(<;.2)@(1!:1)@(<`3:@.('-'-:]))&.>@;@{.@(_64&(<\))) ::1:)]`(]&<&'-')@.(0=#)2}.ARGV

```

Explanation:

* `]`(]&<&'-')@.(0=#)2}.ARGV`: Get the command line arguments, and remove the first two (because those are the interpreter and the script file name). If the resulting list is empty, return `['-']` (i.e., as if the user had passed only `-`), otherwise return the list unchanged.
* `(` ... `::1:)`: if the inner function fails, return `1`, otherwise return whatever the inner function returned.
* `((2*64<#)[`...`)`: evaluate the inner function and throw the result away. Then, if the length of the passed list was not higher than `64`, return `0`, otherwise return `2`.
* `&.>@;@{.@(_64&(<\))`: get at most `64` elements from the list, and for each of them run the following function:
    + `(1!:1)@(<`3:@.('-'-:]))`: if the element was `-`, read the contents of file descriptor `3` (stdin), otherwise read the contents of the file named by that element. If this fails (i.e. file doesn't exist), the code above will catch it and return `1`.
    + `exit@3:`(`...`)@.(1e6>#)@(<;.2)`: split the string on its line endings. If there are 1.000.000 or more lines, exit with status `3`. Otherwise:
        - `,&TAB@(6&":)&.>@>:@i.@#`: generate the numbers for each line, format them in a 6-digit column, and add a `TAB` to the end of each string,
        - `,&.>]`: add each number to the front of each line.
        - `stdout@(,&LF)@;`: then output the whole thing, followed by an extra `LF`.
* `exit`: exit with the return value of that function
> 1 votes

# Answer
# Ruby, 76 bytes

One byte for the `p` flag. Run with `ruby -p nl.rb`.

```
BEGIN{x=$*.size-65}
exit 2if$*.size==x
exit 3if$.>999999
$_="%6d"%$.+?\t+$_

```

stdin or file arguments are handled automatically by Ruby. It already exits with code 1 if a file argument doesn't exist. `$.` is the number of lines that have been read. `$*` is the command line arguments, and the files are popped off as the files are read. The `p` flag executes the `BEGIN` block and wraps the rest of the program inside a while-gets-print loop, using `$_` as the input/output.
> 1 votes

# Answer
# Perl, ~~125~~ 122 bytes

```
@a=@ARGV;for(@a){$i++>63&&exit 2;($_ eq '-'or-e$_)or next;@ARGV=$_;while(<>){$c>1E6-2&&exit 3;printf"%5d\t%s",++$c,$_}say}

```
> 1 votes

# Answer
## Perl, 84 + 2 (`-pl`) = 86 bytes

```
perl -ple'BEGIN{map{-r||exit 1}@ARGV;@ARGV>63&&exit 2}$.>=1e6&&exit 3;$_=printf"%5d\t%s",$.,$_'

```

Deparsed:

```
perl -MO=Deparse -ple'BEGIN{map{-r||exit 1}@ARGV;@ARGV>63&&exit 2}$.>=1e6&&exit 3;$_=printf"%5d\t%s",$.,$_' output.txt; echo $?

BEGIN { $/ = "\n"; $\ = "\n"; }
sub BEGIN {
    map {exit 1 unless -r $_;} @ARGV;
    exit 2 if @ARGV > 63;
}
LINE: while (defined($_ = <ARGV>)) {
    chomp $_;
    exit 3 if $. >= 1000000;
    $_ = printf("%5d\t%s", $., $_);
}
continue {
    die "-p destination: $!\n" unless print $_;
}
-e syntax OK

```

Important to know:

* `-p` wraps the program given with `-e` in the `while`/`continue` loop
* `BEGIN` code will be executed before the (implicit) main part
* file test `-r` also fails if file doesn't exist `!-e` and defaults to testing `$_`, implicitly given in `map { ... } @ARGV`
* `$.` holds the current line number
* rest should be self-explanatory ;)
> 1 votes

# Answer
# C, ~~362~~ 359

Just for the fun of it. ;-) Works with LF or CR/LF linefeeds.

```
#include<stdio.h>
#define R return
#define P printf(
e,t,l;void*f;r(){P"% 6d\t",++l);for(;(t=fgetc(f))^-1&&l<1000000;){if(ferror(f))R 1;P"%c",t);if(t==10)P"% 6d\t",++l);}P"\n");R l<1000000?0:3;}main(int c,char**v){e=c>65?2:0;for(++v;*v||c<2;++v){t=c<2||!strcmp(*v,"-")?f=stdin,0:!(f=fopen(*v,"rb"));if(t||(t=r()))e=!e|(e>t)?t:e;if(f&&f!=stdin)fclose(f);}R e;}

```
> 0 votes

---
Tags: code-golf, string, counting
---