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

• 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

# 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
• I got a different output ("hello" 5 times followed by a list of None's), but the "loop" still works. – ApproachingDarknessFish Jul 11 '14 at 0:26
• did you print the result from the map? because if you don't assign the map function to anything it is run but not stored. – user8777 Jul 11 '14 at 0:28
• This actually prints "hello" 5 times and returns a list of five Nones. I would call it fine, but your result is a little misleading. – seequ Jul 13 '14 at 22:44

# PHP

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

$max = 10;$i = 0;

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

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

eval($e); 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. # 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); } } • There are already two answers which do exactly this. That's one more than necessary. – Peter Taylor Jul 11 '14 at 10:18 ## 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. • Can you explain what this code-snippet does? – CommonGuy Jul 11 '14 at 11:25 • If I could take a stab at this, letters is a built-in vector a-z, print is the built-in print function, and lapply applies the function to every member of a vector/array/matrix/dataframe and then puts them together and returns the result. Interestingly, print returns the printed object as a character vector, so at the interactive prompt this program prints out all the letters a-z and then prints them out again because they are the output of lapply. – raptortech97 Jul 15 '14 at 13:57 # 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. <html> <script> function method() { //do something location.reload(); } </script> <body onload="method()"> </body> </html> It keeps reloading the web page. # 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. # 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. # 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))))) # 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. # 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! 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. # 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. 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
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 :) 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(); } } 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); } } • If you are executing the current method then it's recursion, regardless of how you execute it. – Ross Drew Jul 17 '14 at 7:45 Haskell let x = 0:x in x In GHCI, it prints [0,0,0,.... It uses recursion, but no function calls itself. 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?

C# Linq

Prints all numbers 0 - 10 inclusive

Enumerable.Range(0,11).ToList().ForEach(Console.WriteLine);
• too finite I'd suggest. – Jodrell Jul 17 '14 at 9:29
• Wouldn't ForEach be considered a looping statement? After all, it exists explicitly for the purpose of repeatedly executing code. – celtschk Jul 19 '14 at 7:20
• its not a loop, its a method called ForEach() that is built into the language. :) – Nicholas King Jul 21 '14 at 7:54

# 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... 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);
?>
• Whether it REALLY is recursion depends on what actually happens under the hood with $b=$a. And I'm not sure what that is. – TecBrat Jul 15 '14 at 15:42
• Well, I added a static variable to $a and it persisted, so I guess I'm sunk! I'll leave it up here anyway. (See this: sandbox.onlinephpfunctions.com/code/…) – TecBrat Jul 15 '14 at 15:47 # 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.

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()
{
}
}
• Recursion is still recursion, even if it's indirect. – seequ Jul 17 '14 at 13:39
• @TheRare So, There will always be some recursion or the operation cannot repeat. – Jodrell Jul 17 '14 at 13:51
• I know, I know. I just personally find this a bit too obvious. Not voting in either direction. – seequ Jul 17 '14 at 14:14

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

• What is SAS? I bet it doesn't stand for Scandinavian Airlines as Google tries to assure me. – seequ Jul 17 '14 at 16:27
• en.wikipedia.org/wiki/SAS_(software) – user3490 Jul 18 '14 at 13:22

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

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

• It also prints a [ before the first x, and a ] after the last one. – Paŭlo Ebermann Jul 20 '14 at 9:48
• Edited the code to remove it. – barteks2x Jul 20 '14 at 11:53

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

# 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

# ///

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