# Reinvent the For loop

For loops are used extensively in many languages, but what would you do if no languages supported them?

Create a way to execute a basic for loop without using any repetition structures (for, foreach, while, do, etc).

The basic for loop that you need to replicate is set up like this

for(i=0;i<1000;i++)


You must be able to replicate this without using repetition structures. It must also execute code in your language that would be in the body of the loop. Any form of eval is allowed, though it may not execute the for loop on its own.

You can test your code by having it print i with a space 100 times, add this test case to the end of your answer to verify your code with others.

There are no restrictions on what exactly it has to be, all it needs to do is replicate the for loop.

Winner will be decided based on upvotes at the time that it is chosen.

-
100 times or 1000? Or 100 000 times? – user unknown Feb 19 '11 at 6:50
I find the problem too undefined. You say “without using any repetition structures” and only give examples (but not an extensive list) of such prohibited structures. The answers provided so far use recursion or goto, both of which I would classify as “repetition structures”, but it can be debated. Without a proper definition of what is allowed and what isn’t, this question is not interesting. – Timwi Mar 8 '11 at 14:34
gotos, recursion... – Mateen Ulhaq Mar 10 '11 at 2:29

## C, 45 chars without goto, if, for, ...

Not the smallest solution, but I find this way of doing it quite interesting in C :)

Doesn't use goto, if, for, or any other kind of control structures.

The function by itself (45 chars):

m(){int (*a[])()={m,exit};i++;(*a[i>999])();}


A compilable, working program:

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

int i=0;
m(){int (*a[])()={m,exit};i++;printf("%i ",i);(*a[i>999])();}

int main()
{
m();
}

-
A function call is a "control structure." Right? – EfForEffort May 25 '12 at 0:21
@Denis Bueno: No, a control structure is stuff like while, do, for, if... – houbysoft May 25 '12 at 1:54
Can you please include an explanation? I got a bit lost. – Rees Jan 11 '14 at 15:21
This is a bit late, but @Rees: int (*a[])()={m,exit} is an array of function pointers. m is called which increments and prints i (set to 1, 2, 3, ...) and calls a function from the array of function pointers. The call (*a[i>999])(); will expand to (*a[0])(); or (*a[1])(); since C will use the value of i>999 as an integer depending on whether it is true or false (1 or 0). It'll call m until i>999 is true, then call exit. Nice use of function pointers. – aglasser Jul 17 '14 at 13:59

This is more like inventing the for loop, because there is no such nonsense in Haskell :P.

mapM_(putStr.(' ':).show)[0..999]

-
forM_ is just mapM_ with the arguments flipped, so this might be cheating. ;) – Dan Burton Mar 11 '11 at 5:29

## GCC - 106 95 chars

#define FOR(i,l,h)auto F();L(F,l,h);int F(i)
L(int f(int),int l,int h){l<=h?f(l),L(f,l+1,h):0;}


Unlike the other C solutions where you have to declare a callback, this one does it for you automagically:

FOR(i, 1, 10) {
printf("%d\n", i);
}


It works by using GCC's nested function extension. Namely, it forward-declares the nested function F, passes it to the looping function L, and then starts the definition of F, leaving the braces for the user to add.

One beautiful thing about nested functions in GCC is that they support downward funargs, meaning the illusion is nearly complete:

long n = 1;
FOR(i, 1, 10) {
n *= i;
}
printf("%ld\n", n); // 3628800


There is one major caveat: if you use FOR twice in the same scope, you'll get a conflict (namely, it will compile, but all the FOR loops will share one loop body). To allow multiple FOR loops in the same scope, we'll need 69 65 more characters:

175 160 chars:

#define FOR(i,l,h)F(i,l,h,__COUNTER__)
#define F(i,l,h,f)auto N(f)();L(N(f),l,h);int N(f)(i)
#define N(n)F##n
L(int f(int),int l,int h){l<=h?f(l),L(f,l+1,h):0;}

-
+1 for 'automagically' – lesderid Apr 25 '12 at 21:46
This really is closest to an actual for loop. Great one. – tomsmeding Dec 8 '13 at 21:52
This is brilliant. – Cruncher Dec 9 '13 at 14:58

## C, 21 characters

f(){if(c++<999)f();}


For example:

#include <stdio.h>
int c = 0;
f()
{
printf("%d ", c);
if (c++<999) f();
}
int main(void)
{
f();
}


Outputs:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... 998 999

-
Without a main() in the first block, the code won't link. Therefore I think it should be included in the entry. – Nathan Osman Feb 19 '11 at 6:11
@George: I think it's fair omitting main() in this case because the question says "Create a way to execute" not "make a complete program" as in other problems. – Eelvex Feb 19 '11 at 15:46
remove void  then it will be 26 characters only. – Prince John Wesley Mar 25 '11 at 3:45

## x86 assembly, 12 11 bytes' worth of instructions

66 31 c0                xor    %ax,%ax
<body>                ; involving %ax
66 40                   inc    %ax
66 3d  e8 03            cmp    $1000,%ax 75 ?? jne <body>  - A pity they're asked in ascending order... I'm pretty sure it would be shorter descending. – J B Feb 19 '11 at 0:28 @J B: Yes -- in descending order, you'd normally use the loop instruction: mov cx, 1000\nx: ... loop x – Jerry Coffin Feb 20 '11 at 6:47 ## C# — no recursion, no goto (using the Y combinator from lambda calculus) class Program { delegate Func<TInput, TResult> Lambda<TInput, TResult>(Lambda<TInput, TResult> f); static Func<TInput, TResult> Y<TInput, TResult>(Func<Func<TInput, TResult>, Func<TInput, TResult>> f) { Lambda<TInput, TResult> y = r => n => f(r(r))(n); return y(y); } static void Main() { Func<int, int> fibonacci = Y<int, int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n); Func<int, int> factorial = Y<int, int>(f => n => n == 0 ? 1 : n * f(n - 1)); // Executes “fibonacci” 10 times, yielding 55 Console.WriteLine(fibonacci(10)); // Executes “factorial” 5 times, yielding 120 Console.WriteLine(factorial(5)); } }  - One might argue that the Y operator implements recursion… – Bergi Jul 12 '14 at 22:02 # JavaScript, 34 characters This assumes the actual printing function is not part of the for loop. parameterized recursion (43): function f(i,m,c){if (i<m){c();f(++i,m,c)}} function f(i, max, callback) { if (i<max) { callback(); f(++i,max,callback); } }  reverse recursion (36): assumes max >= 0 function f(m,c){if(m){c() f(--m,c)}} function f(max,callback) { if(max) { callback(); f(--max,callback); } }  ternary operator (34) function f(m,c) {m?c()&f(--m,c):0}  - function f(m,c){m&&c()&f(--m,c)} - You could make that 32 bytes :) – pimvdb Oct 18 '11 at 17:42 ## Ruby 1.9 - 51 characters def f a,b,c,&d a[] k=->{d[];c[];redo if b[]} k[]end  This is a lot larger than other entries, but I think it captures the essence of the question better. In effect this allows you to write code almost exactly like the example: def f a,b,c,&d a[] k=->{d[];c[];redo if b[]} k[]end i = 0 # Have to pre-declare i to have the closures work properly f(proc{ i = 0 }, proc{ i < 1000 }, proc{ i += 1}) do p i end # Been a long time since I've actually used for's so took a long # time to think of a non-trivial use. j, sum = 0, 0 # Pre-declare variables for the closures goal = 1000 f(proc{ j = 1; sum = 1 }, proc{ sum < goal }, proc{ j += 1 }) do sum = sum * j end puts "The next largest factorial after #{goal} is #{j-1}! at #{sum}"  - ### Yet another Scala variant Since Scala allows to use non-ASCII characters, we can implement real for :) (o is cyrillic). def fоr(s:Unit,c: ⇒Boolean,e: ⇒Unit)(b: ⇒Unit):Unit=if(c){b;e;fоr(0,c,e)(b)}  Test: var i:Int = _ fоr (i = 0, i < 1000, i += 1) { print(i + " ") }  - # C#, 70 57 characters C# isn't the weapon of choice for code golf, but I thought I'd try it out: void f(int i,Func<int,bool>j,int k){if(j(i)) f(i+k,j,k);}  This doesn't only perform the task of counting up to 1000; rather, it attempts to actually replicate for loop behavior for any task. That seemed somewhat closer to the intent of the challenge, but maybe that's just me. Expanded: void f(int i, Func<int, bool> j, int k) { if (j(i)) { f(i + k, j, k); } }  Usage is very close to for-loop syntax: f(0, i => i < 1000, 1);  - ## Python Specific case: exec("print i,"+";")*1000  And in general: exec("f"+";")*1000  where 'f' is your code. Proabably doesn't work for all cases. - NameError: name 'i' is not defined – J B Feb 19 '11 at 0:45 I've kind of fixed it. Plus, I assumed that i was predefined. – user611 Feb 19 '11 at 0:57 If it's predefined, it's not going to change with the iteration. That's not how a for loop works. – J B Feb 19 '11 at 1:02 Fair point. I imagine it would need ;i=+1 after the comma. I did say it wouldn't work with all cases. – user611 Feb 19 '11 at 1:11 exec 'i=0;'+1000*'print i;i+=1;' would do the job. – flonk Jan 13 '14 at 13:35 C: 33 chars for the base for loop (assuming goto is allowed) int i=0;s:if(i<1000){/*code inside for loop here*/i++;goto s;} int i=0;s:if(i<1000){printf("%d ",i);i++;goto s;}  - I shall bear great shame for this, but here it is in Linux shell: cat -An /dev/urandom|head -n1000|cut -f1  40 characters. - Prints linebreaks => disqualification! :) – user unknown Feb 19 '11 at 7:08 Here's your loop using Brainfuck, which is probably cheating: ,[.,]  - :) Unfair though. – tomsmeding Dec 8 '13 at 21:52 ## JavaScript - 39 characters in test case Chrome, Opera, and IE: eval(s="i<1e3&&eval(s,print(i++))",i=0). This fails with "call stack size exceeded" on Safari and "too much recursion" on Firefox. Firefox: (function f()i<1e3&&f(print(i++)))(i=0). This uses Mozilla's non-standard "expression closure" feature to eliminate a pair of curly braces. Note: Change print(i++) to alert(i++) if you need to. You can change 1e3 to 100 to reduce the number of iterations for Safari. - Putting the print call inside the eval call is really clever. – Justin Morgan Jan 7 '14 at 22:07 ## QBasic (24 characters) 1?i:i=i+1:IF i<1E3THEN 1  expands to: 1 PRINT i: i = i + 1: IF i < 1000! THEN 1  Note: This assumes that i still has its original value of 0. - ## J, ?<10 chars f^:1000  In J there are (almost) no loops; instead, one usually uses arrays and implicit loops through them. For example, to sum the integers 1..100, you apply (/) the "verb" plus (+) to the array 1..100 (i.101) +/i.101 5050  To display the numbers 0..99, we just construct the array: i.100 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ...  ^: is the "power" verb; f^:1000 is something like exec()*1000 in python. - ## C#, 58 characters Update: D'oh...appears this is a virtually identical answer to Eelvex who beat me by a few minutes. Not very clever - just simple recursion in .NET. void f(int c,int m){Console.Write(c+" ");if(c++<m)f(c,m);}  Or taking out the body of the "for loop" (35 characters): void f(int c,int m)if(c++<m)f(c,m);  Allows to seed the initial value and the max value. - # Scala Inspired from Nemo157's answer: def myfor(test: =>Boolean, inc: =>Unit)(stmts: =>Unit) : Unit = if (test) { stmts inc myfor(test, inc)(stmts) }  And this can be used like this: var i = 0 myfor(i<1000, i+=1) { print(i+" ") }  Golfed (62) : def f(t: =>Boolean,i: =>Unit)(s: =>Unit){if(t){s;i;f(t,i)(s)}}  Or: def myfor[A](init: A, test: (A)=>Boolean, inc: (A)=>(A))(stmts: =>Unit) : Unit = if (test(init)) { stmts myfor(inc(init), test, inc)(stmts) } myfor[Int](0, _<10, _+1) { println("loop") }  - ## PowerShell 18 filter p{$i=$_;$i}


1 - 10

PS C:\> (1..100 | p)-join' '
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 6
4 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100


Yeah, it's completely useless and you have to rewrite the function to do anything useful. But isn't that kind of the point? :)

-
Prints newlines as delimiters? ... print i with a space 1 ... - disqualification. :) – user unknown Feb 19 '11 at 7:02
filter p{"$_ "} --- :) – Ty Auvil Feb 19 '11 at 16:23 I'm not sure if this should be disqualified, as it's technically (ab)using the pipeline as if it was foreach. – Iszi Dec 9 '13 at 15:14 Clojure (map #(print (str % " ")) (range 1 (inc 100))) Replace print with the function to execute. Use (inc 100) or 101 for the last value. - ## Perl, 21 characters map{print"$_ "}0..999

-
Mapping is a type of looping. Don't cheat! :-P – Chris Jester-Young Feb 19 '11 at 2:58
This comment is nonsense, since we have to write something which is equivalent to a for-loop. If we met the criteria, it will be always cheating, or what will make the difference? Explicit gotos? Recursion? – user unknown Feb 19 '11 at 6:56
@Chris well I explicitely asked the OP in the chat before answering that one. – J B Feb 19 '11 at 9:26

# Perl most simple - 18 chars (ok, cheating)

print"@{[0..999]}"


output: 0 1 2 3 ... 998 999

but:

# Perl regex/goatse op (real pseudoloop) - 39 (16) chars

()="@{[0..999]}"=~/\d+(?{print"$& "})/g  ### the 'base loop' beeing 16 chars ()= =~/\d+(?{ })/g  output: 0 1 2 3 ... 998 999 Regards rbo - # Javascript - 86 chars e=eval,n=function(j,k,c){if(e(j))e(k),c(),n(j,k,c)},f=function(i,j,k,c){e(i),n(j,k,c)}  Maybe not the shortest javascript solution, but it replicates iterator declaration, iterator manipulation as well as a looping condition. Example use case: f('a = 0', 'a < 9', 'a++', function() { console.log(a); });  - ;; for (int index=1, result=1; !cmp(result, max); index=incr(index)) result=body(index,result); ((lambda (index result cmp max body incr) ((lambda (f n i) (if (cmp i max) n (f f (body i n) (incr i)))) (lambda (f n i) (if (cmp i max) n (f f (body i n) (incr i)))) result index)) 1 1 > 1000 (lambda (i n) (printf "i:~a~nn:~a~n" i n) (* n i)) (lambda (x) (+ x 1)))  - Please label the language used for this answer. – Nathan Osman Feb 20 '11 at 21:50 ## LISP, 91 characters (defun m(x)(if(= 1000(length x))x(m(append x(list(1+(car(last x)))))))) (mapcar #'f(m'(0)))  It could be shorter with labels. Example usage: (defun f(x) (format t "~a " x)) (mapcar #'f (m '(0))) 0 1 2 3 4 5 6 7 8 9 10 11 12 ... 997 998 999  - bash: echo {1..1000}  14 chars. - ## Python3 - 27 chars any(map(print,range(1000)))  - Cool. For the nice output: print(" ".join(map(str,range(1000)))) – Wok Feb 19 '11 at 20:53 Groovy: (0..1000).each{ print "${it} " }

-
each is foreach => disqualified :) println is printing with newline, not space => disqualified. ;) – user unknown Feb 19 '11 at 7:20
Which is silly. Iteration is not a loop even though they contain 4 letters which are similar. Iteration = processing data in memory = what computers are built to do. – user615 Feb 19 '11 at 14:11

## Windows Batch File, 65

set I=%S%
:l
if %I% GEQ %E% goto :eof
call %C%
set /a I+=1
goto l


Test file:

@echo off
set S=0
set E=100
set "C=<nul set /p X=%%I%% "
call for.cmd


Can save two bytes if the loop always starts at 0.

-