23
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 100 times or 1000? Or 100 000 times? \$\endgroup\$ – user unknown Feb 19 '11 at 6:50
  • 10
    \$\begingroup\$ 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. \$\endgroup\$ – Timwi Mar 8 '11 at 14:34
  • \$\begingroup\$ gotos, recursion... \$\endgroup\$ – Mateen Ulhaq Mar 10 '11 at 2:29
  • \$\begingroup\$ I am voting to close this as off-topic because we require objective validity criteria for all challenges. As it stands, there is no clear way to determine the validity of a submission. Additionally, there is no specification of the behavior of a valid submission. \$\endgroup\$ – Mego May 20 '16 at 5:35

61 Answers 61

1
\$\begingroup\$

Perl (23 chars.):

print join " ",(0..999);*

or same Perl but in simpler yet more lengthy and recursive words:

sub i {($s,$e)=@_; return if $s==$e; print "$s "; i($s+1,$e)}

i(0,1000);
\$\endgroup\$
1
\$\begingroup\$

C#, 70 chars

Enumerable.Range(0,999).ToList().ForEach(x=>Console.WriteLine(x+" "));

This can probably be golfed down, but it's the best I could come up with quickly.

\$\endgroup\$
  • \$\begingroup\$ Obviously never going to beat Perl, but I didn't see the Perl comment before I posted mine. \$\endgroup\$ – B.R. Feb 19 '11 at 0:07
  • \$\begingroup\$ The code uses a foreach loop, which isn't allowed in the first post. \$\endgroup\$ – Kevin Brown Feb 19 '11 at 1:32
  • \$\begingroup\$ @Bass: no it doesn't. It calls a method that happens to be called ForEach. \$\endgroup\$ – R. Martinho Fernandes Feb 19 '11 at 5:31
  • \$\begingroup\$ @Martinho, so .each in Ruby and ForEach-Object in PowerShell is fine as well? There are languages that don't even have that many keywords, actually. \$\endgroup\$ – Joey Feb 19 '11 at 17:18
  • \$\begingroup\$ @Joey: look at how many existing answers use .each, map, range generators, etc. They're just black boxes. Who says they are not using gotos? \$\endgroup\$ – R. Martinho Fernandes Feb 19 '11 at 19:29
1
\$\begingroup\$

QuickBASIC, 103 characters

10 IF i < 1000 THEN PRINT MID$(STR$(i) + SPACE$(1), 2, ABS(i < 100) * 5); : i = i + 1: GOTO 10 ELSE END
\$\endgroup\$
  • \$\begingroup\$ Oh dear, after re-reading the requirements it looks like only the numbers 0 through 99 should be printed. Revised entry (and I think I'll have to take a shower after THIS hack): 10 IF i < 1000 THEN PRINT MID$(STR$(i) + SPACE$(1), 2, ABS(i < 100) * 5); : i = i + 1: GOTO 10 ELSE END \$\endgroup\$ – user609 Feb 19 '11 at 1:27
1
\$\begingroup\$

Java with Lambda — 259 characters

I just built the prerelease Java langtools with the experimental lambda support that has recently been canceled for JDK 7 and pushed back until JDK 8 in 2012 (boo!) and wanted to try it out.

Formatted nicely, this version clocks in at 304 characters. If you reformat it so all the code of the interface is on one line and the class is on another, it gets down to 259 characters. I'm sure you could golf it down lower (shorten the identifiers, for starters), but Java is never going to be competitive at golf, so why obfuscate it.

interface Fore {
    void exec(int i);
}

public class ForLoop {
    public static void main(String[] args) {
        loop(1, 10, #{ int i -> System.out.println(i) });
    }

    public static void loop(int x, int max, Fore fore) {
        fore.exec(x);
        if (x < max) loop(x+1, max, fore);
    }
}

I just wanted to demonstrate what will be possible with lambdas in Java SE 8. The call to loop could be written with an anonymous inner class, instead:

loop(1, 10, new Fore() {
    public void exec(int i) {
        System.out.println(i);
    }
});

Yuck.

The syntax for lambdas in Java hasn't been settled yet; this is just what works with the current dev build of javac. Thanks to those who are working to make it happen. Java should have gotten lambdas and closures years ago. Alas.

\$\endgroup\$
1
\$\begingroup\$

C

(not really golfing, but fun)

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

int main() {
    jmp_buf b;
    int i;
    if ((i = setjmp(b)) < 100) {
        printf("%d\n", i);
        longjmp(b, i + 1); 
    }
} 
\$\endgroup\$
  • \$\begingroup\$ At least it doesn't use goto. \$\endgroup\$ – Joey Adams Mar 19 '11 at 18:29
1
\$\begingroup\$

JavaScript, 63 characters

(function i(s,r){r+=s+' ';s++<1e3?i(s,r):console.log(r)})(0,'')

with proper console output

\$\endgroup\$
1
\$\begingroup\$

Javascript This one supports a few extra things, with plenty still missing. Breaks after 3000 iterations cuz it's recursive.

function r(a,c,b,o,q,f) {var d=c=='<'?a<b:(c=='>'?a>b:(c=='=='?a==b:(c=='!='?a!=b:null)));if(d){f(a);a=o=='+'?a+q:(o=='-'?a-q:(o=='*'?a*q:(o=='/'?a/q:null)));r(a,c,b,o,q,f);}}
//params:  a = iterator start
// c = comparison type (supports >, <, ==, !=)
// b = iterator compare
// o = iterator operation (+, -, *, /)
// q = increment or whatever you call it
// f = function to execute each successful iteration

// from 0 to 99
r(0, '<', 100, '+', 1, function(i) {document.write(i + ' ');});
// from 100 to 1
r(100, '>', 0, '-', 1, function(i) {document.write(i + ' ');});
// powers of 10
r(1, '!=', 1000000, '*', 10, function(i) {document.write(i + ' ');});
\$\endgroup\$
1
\$\begingroup\$

R - 11 characters

General case:

f(1:1000)

Where f is your function.

Specific case:

cat(1:1000)
\$\endgroup\$
1
\$\begingroup\$

C 45 characters including printout

Compiles, links, and runs as-is; no need to define a separate function and then call it, adding to source size.

main(a){printf("%d ",a-1);a<1000&&main(a+1);}
\$\endgroup\$
1
\$\begingroup\$

Javascript (44 chars.):

Another rather pointless option, but then who said golf had to have a point :) Plus I gained something new... I never realised you could get away with i+++

eval(Array((i=0)+1e3).join('i+++" "+')+'i')

I also learned that running .map and .forEach on an initialised undefined filled Array does nothing... at least in FireFox anyway

Array(1000).forEach(function(){ /* this code is never executed :( */ })
\$\endgroup\$
  • \$\begingroup\$ From MDN - callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. \$\endgroup\$ – Gareth Nov 20 '12 at 9:01
  • \$\begingroup\$ @Gareth yep thanks for the quote, I assumed as much, was just a little unexpected.. and rather annoying from a codegolf point of view :) \$\endgroup\$ – Pebbl Nov 20 '12 at 9:22
1
\$\begingroup\$

Javascript, 71. No if, for, or recursive function

function f(i,c,b){a=[]
eval(s=b+";a[++i]=s;a=a.slice(0,c);eval(a[i])")}

Test:

f(0,1000,'console.log(i)')
\$\endgroup\$
1
\$\begingroup\$

Spaghetti PHP 44

<?$i=0;a:if($i<1001){echo $i++." ";goto a;}

enter image description here

\$\endgroup\$
1
\$\begingroup\$

Python 2.7, 60 Bytes with command-line parameter

Prints 'O' to the console:

import sys
def l(t,m):
 print 'O'
  if t!=m:
   l(t+1,m)
l(0,int(sys.argv[0]))

EDIT: Realised it didn't work, so byte count has gone up to fix On another note, here's a 127 byte version, including print function, that will let you actually call functions with one argument

import sys
def println(a):
print(a)
def l(t,m,f,a): 
    f(a) 
    if t!=m:
        l(t+1,m,f,a)
p=println
l(0,int(sys.argv[1]),p,"there")
\$\endgroup\$
1
\$\begingroup\$

sh

cat -An /dev/urandom|head -n1000|cut -f1|xargs
\$\endgroup\$
  • \$\begingroup\$ You can generate infinite lines with "yes". Try "yes ''|head -n1000|cat -n|xargs" \$\endgroup\$ – swstephe Dec 22 '14 at 19:42
0
\$\begingroup\$

Python 2.x - 17 chars

print range(1000)
\$\endgroup\$
  • \$\begingroup\$ You need a for loop: print " ".join(`i` for i in range(1000)) \$\endgroup\$ – Wok Feb 19 '11 at 9:35
  • \$\begingroup\$ @wok: the challenge is to not use for-loops. \$\endgroup\$ – JPvdMerwe Feb 20 '11 at 16:26
0
\$\begingroup\$

Language = C

just loop - 59 characters

(int(*)())\x66\x31\xc0\x66\x40\x66\x3d\xe8\x03\x75\xf8\xc3"

loop+call - 92 characters

(int(*)())"\x66\x31\xc0\x8b\x5c\x24\x04\x66\x40\x50\xff\xd3\x58\x66\x3d\xe8\x03\x75\xf4\xc3"

Example usage:

#include <stdio.h>

void disp(int n){printf("%d ", n&(0xffff));}

int main(){
    ((int(*)())"\x66\x31\xc0\x8b\x5c\x24\x04\x66\x40\x50\xff\xd3\x58\x66\x3d\xe8\x03\x75\xf4\xc3")(&disp);
    return 0;
}

This will only work on x86 machines. Tested with gcc (and works on codepad.org -> http://codepad.org/uyhFR9XU)

int fn(int n){ // n is at esp+4

    xor %ax, %ax ; zeros ax
    mov 4(%esp), %ebx ; saves esp+4 (addr of n) to ebx

    body:
    inc %ax ; add one to ax (this will print from 1 to 1000 instead of 0-999)
    push %eax ; pushes eax onto the stack
    call *%ebx ; calls n, which should contain &disp
    pop %eax ; pop eax off the stack assuming disp did not use eax
    cmp $1000, %ax ; compare
    jne body ; if not 1000, goto body

    ret
}
\$\endgroup\$
  • 2
    \$\begingroup\$ And probably should fail when DEP is enabled. \$\endgroup\$ – Joey Feb 19 '11 at 17:37
  • \$\begingroup\$ Can you include the char count and language? \$\endgroup\$ – R. Martinho Fernandes Feb 19 '11 at 19:43
  • \$\begingroup\$ K, information added \$\endgroup\$ – Lee Feb 19 '11 at 21:21
0
\$\begingroup\$

Scala:

(1 to 100)mkString" "

21 chars not that ugly:

(1 to 100) mkString " "
\$\endgroup\$
0
\$\begingroup\$

APL (26)

{(⊃⍵)>⊃⌽⍵:⍬⋄⍺⍺∇⍵+1 0⊣⍺⍺⊃⍵}

Usage:

<function> {(⊃⍵)>⊃⌽⍵:⍬⋄⍺⍺∇⍵+1 0⊣⍺⍺⊃⍵} <start> <end>

i.e.

{⍞←⍵ ' '} {(⊃⍵)>⊃⌽⍵:⍬⋄⍺⍺∇⍵+1 0⊣⍺⍺⊃⍵} 1 100

prints the numbers from 1 to 100.

\$\endgroup\$
0
\$\begingroup\$

VB11 (95c)

Dim F As Action(Of Integer, Integer, Action(Of Integer)) =
  Sub(i, m, a)
    If i > m Then Return
    a(i)
    F(i + 1, i, a)
  End Sub

And in use

 F(1, 1000, Sub(X) Console.WriteLine(X))

C# 52

f(int i,int m, action<int> a){if(i<=m){a(i);f(i-1,m,a);}
\$\endgroup\$
0
\$\begingroup\$

Python 2.6 (42)

def f(i,p,j=0):j<i and(p(j)or f(i,p,j+1))

# Test:
def do(i):
    print i
f(100,do)

This for-Function also includes the break command:

def do(i):
    print i
    if i==7:
        return True
        # break
f(100,do)
\$\endgroup\$
0
\$\begingroup\$

clang (152)

Tested with Apple clang version 4.0

bfor(int n,void(^b)(int)){
    __block void(^e)(int,int)=^(int l,int h){
        int m;
        h<l?:(m=(l+h)/2,e(l,m-1),b(m),e(m+1,h));
    };
    e(0,n-1);
}

Usage:

main(){
    bfor(100,^(int i){
        printf("%d ", i);
    });
    puts("");
}

The stack depth is log2 of the count due to the binary tree and thus it's unlikely to overflow due to recursion.

\$\endgroup\$
0
\$\begingroup\$

Ti-84 Basic, 34

Here, > represents the calculator's STO-> button.

:-1>I:Lbl A:I+1>I:If I<1000:Goto A
\$\endgroup\$
0
\$\begingroup\$

Golf-Basic 84, 23 characters

:-1_Il`A:I++I@I<1000o`A
\$\endgroup\$
0
\$\begingroup\$

Lua, 59

local function f(x)if x<1000 then return f(x+1)end end f(0)

The loop body is located right after the then. This does not overflow stack because of the tail call optimization.

Test case:

local function f(x)if x<1000 then print(x)return f(x+1)end end f(0)
\$\endgroup\$
0
\$\begingroup\$

Same as @houbysoft, but in C++.

#include <iostream>
#include <vector>

int main(int argc, char *argv[])
{
    int i = 0;
    std::function<int()> m = [&i, &m]()->int {
        std::vector<std::function<int()>> functors;
        functors.push_back(m);
        functors.push_back([]()->int{return 0;});
        i++;
        std::cout << i << std::endl;
        functors[i>999]();
        return i;
    };
    m();
    return 0;
}

And Objective C (Just C using blocks, actually...)

#import <Foundation/Foundation.h>

int main(int argc, char *argv[])
{
    __block int i = 0;
    __block int (^m)();
    m = ^() {
        int (^a[])() = {m, ^(){return 0;}};
        i++;
        NSLog(@"i: %d", i);
        a[i>9]();
        return i;
    };
    m();
    return 0;
}
\$\endgroup\$
0
\$\begingroup\$

Nemerle (?c)

macro for (init, cond, change, body)
syntax ("for", "(", init, ";", cond, ";", change, ")", body)
{
 <[ 
   $init;
   def loop () : void
   {
     if ($cond) { $body; $change; loop() } 
        else ()
   };
   loop ()
  ]>
}

Usage

 for (mutable i = 0, i < 10, i++, printf ("%d", i))
\$\endgroup\$
0
\$\begingroup\$

Lua (63 chars)

function F(n,f,...)if n>0 then f(...)return F(n-1,f,...)end end

Slightly longer, but more generic, than @mniip's version. Use like F(1000,print,' ').

\$\endgroup\$
0
\$\begingroup\$

C - 48 characters

Compilable code.

main(int i){i^1002&&main(i+1);printf("%i",i-2);}
\$\endgroup\$
0
\$\begingroup\$

Objective-C 58 Characters (Or 45...)

int i;
-(void)f {
    NSLog(@"%d",i++);
    if (i<1000) [self f];
}

[self f];

*13 chars went on printing i, so only the for-loop is actually 45...

\$\endgroup\$
0
\$\begingroup\$

CPython 2, 158 bytes

(Yes, this is both implementation and version specific)

class K(object):
 def __init__(s,b,c,e,n):
  if not n:n={};exec b in n
  else:exec e in n
  s.n=n;s.c=c;s.e=e
 def __del__(s):eval(s.c,s.n)or K(0,s.c,s.e,s.n)

Example usage:

K('i=55','i<88','i+=1;print i`,0)
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.