# Loop without 'looping' [closed]

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.

## closed as too broad by Mego♦, Rɪᴋᴇʀ, DJMcMayhem♦, NoOneIsHere, DennisJul 6 '16 at 22:25

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

## locked by DennisJul 6 '16 at 22:28

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. See the help center for guidance on writing a good question.

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

# 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. • The question explicitly forbade "A programming language statement which allows code to be repeatedly executed" like redo. – msh210 Jan 4 '16 at 19:31 # 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(); }  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)  • Also __getattr__ or __eq__. :P – cjfaure Jul 10 '14 at 12:15 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  # 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) # 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 evals: (defmacro macroloop (s n) (if (> (eval n) 0) (progn (macroexpand (macroloop ,s ,(- n 1)) ) (print s) ) ) ) (macroloop "hello world" 10)  • Better not use this for too long loops. – seequ Jul 10 '14 at 16:30 • Yup, same goes for (non-tail) recursion. :) – Arne Jul 10 '14 at 21:03 SQL (oracle 10g or above) select level from dual connect by 1=1;  This will generate rows from 1 to infinite. # php Very simple method, this happens every once in a while when not paying attention: header('Location: thisPage.php');  • shouldn't it be header('Location: '.$_SERVER['PHP_SELF']);? – eithed Jul 11 '14 at 21:41
• Doesn't really matter. Choose this because I thought this might look simpler – Martijn Jul 12 '14 at 11:28

# JavaScript

Small loop when listening on DOM tree modification :

var int=0;
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.

Public Event e()

Public Function a() Handles Me.e

RaiseEvent e()

End Function

a()

• Is this Visual Basic? – jimmy23013 Jul 11 '14 at 16:01

# 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]);
}


## Java Swing

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

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


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.

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;
{

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

}

});

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

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

});

//let the "loop" finish
Console.WriteLine(mycounter);

• the function doesn't call itself but it makes a new thread that runs the calling action – user29252 Jul 11 '14 at 20:26
• the second action takes the first as a parameter, and runs it over and over until the counter hits the target,all while the main thread of the program is suspended and waiting for the target to be hit so it can be awoken. Yes it's an intentional race condition but it's safe. – user29252 Jul 11 '14 at 20:30
• to clarify, the first action is running a copy of itself over and over, by creating new threads in the thread pool, and this is why I had to create two separate actions, as an action cannot possibly know the definition of itself inside of its own declaration unless it has been declared already elsewhere. – user29252 Jul 11 '14 at 20:59

## 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;

</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.

## 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.

# 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!


## 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

## 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.

• What language is this? – raptortech97 Jul 15 '14 at 13:59
• @raptortech97 JavaScript – Cilan Jul 15 '14 at 15:56

## Javascript

<script>
var button = document.createElement('button');
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.

# JavaScript

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

• First glance I read "evil array" – Mark Jeronimus Sep 12 '15 at 16:23

## 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 POKEs specify the line number
The last POKE specifies which statement on that line, and causes the goto to execute

# 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.

## 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

# Unlambda

cccc


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

# ><>

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

!


# Java

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


# 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

; return
RTS

END START


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

# 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.

• It complies with the rules: 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). – CousinCocaine Jul 10 '14 at 17:40
• Not very general, is it? Also I would argue that is just one non-repeated command. – seequ Jul 10 '14 at 17:40
• @TheRare, what do you mean? – CousinCocaine Jul 10 '14 at 17:41
• You're just calling cat with an infinite source. I wouldn't say you're repeatedly calling cat. – seequ Jul 10 '14 at 17:42
• It does what is asked: "repeatedly executes code without using any repetition structures such as while, for, do while, foreach or goto". I agree, it feels like cheating, but it is not. – CousinCocaine Jul 10 '14 at 18:44