# 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

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

• FYI, your code is not guaranteed to work unless you declare count as volatile. I've never seen an implementation that screws it up but the standard says it's not guaranteed. – Joshua Jul 13 '14 at 22:11
• @Joshua Oops, good catch. – fluffy Jul 13 '14 at 22:23
• Skirting the edge of 'goto' but I reckon it counts. – Alchymist Jul 14 '14 at 22:37
• @Alchymist setjmp/longjmp are just a high-level wrapper to the platform-dependent stack-manipulation tricks that have appeared in a few other answers. I only posted this answer for completeness' sake. – fluffy Jul 14 '14 at 22:45

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

# JS

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

(function(){
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
$('#go').trigger('click'); });  • Isn't that againt the "no recursion"-rule? – german_guy Jul 10 '14 at 13:20 • Not by the definition of recursion provided... My function does not call itself, either directly or indirectly. It simply triggers an event that it is tied to. – John Chrysostom Jul 10 '14 at 15:38 • You could add .trigger('click'); after the click() function to auto-init :) – Martijn Jul 11 '14 at 8:53 # 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. # 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... • Is this C? Can't tell – CailinP Jul 11 '14 at 0:34 • @CailinP Whoops forgot to mention it was Python – Hovercouch Jul 11 '14 at 0:36 • Makes sense. I like this! – CailinP Jul 11 '14 at 0:37 # 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. 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, • This is indirect recursion, so your answer is invalid – William Barbosa Jul 11 '14 at 12:20 • OP: "And the definition of recursion for this question will be your standard recursive function definition: A function that calls itself." The answer is valid, if a little long for what it does. – raptortech97 Jul 15 '14 at 13:53 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 );  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. 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  # 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.

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

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

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

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


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