# Reinvent the For loop [closed]

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? Commented Feb 19, 2011 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. Commented Mar 8, 2011 at 14:34
• gotos, recursion... Commented Mar 10, 2011 at 2:29
• 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.
– user45941
Commented May 20, 2016 at 5:35

## 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? Commented May 25, 2012 at 0:21
• @Denis Bueno: No, a control structure is stuff like while, do, for, if... Commented May 25, 2012 at 1:54
• Can you please include an explanation? I got a bit lost.
– Rees
Commented Jan 11, 2014 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. Commented Jul 17, 2014 at 13:59
• You can remove that space. Commented Feb 12, 2020 at 23:52

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. ;) Commented Mar 11, 2011 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;}


## 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. Commented Feb 19, 2011 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. Commented Feb 19, 2011 at 15:46
• remove void  then it will be 26 characters only. Commented Mar 25, 2011 at 3:45

## 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… Commented Jul 12, 2014 at 22:02

## 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 Commented Feb 19, 2011 at 0:28 • @J B: Yes -- in descending order, you'd normally use the loop instruction: mov cx, 1000\nx: ... loop x Commented Feb 20, 2011 at 6:47 ### 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 + " ") }  ## 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}"  # 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 :) Commented Oct 18, 2011 at 17:42 # 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 Commented Feb 19, 2011 at 0:45 • I've kind of fixed it. Plus, I assumed that i was predefined. – user611 Commented Feb 19, 2011 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 Commented Feb 19, 2011 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 Commented Feb 19, 2011 at 1:11 • exec 'i=0;'+1000*'print i;i+=1;' would do the job. Commented Jan 13, 2014 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! :) Commented Feb 19, 2011 at 7:08 ## 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. :) Commented Feb 19, 2011 at 7:02
• filter p{"$_ "} --- :) Commented Feb 19, 2011 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 Commented Dec 9, 2013 at 15:14 Here's your loop using Brainfuck, which is probably cheating: ,[.,]  • :) Unfair though. Commented Dec 8, 2013 at 21:52 # C (No recursion, no goto's) #include <stdio.h> int main() { puts("0 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 64 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999"); return 0; }  Completely according to the definition, isn't it? • It replicates the output, but it does not really match the specification of a for loop. However, I think its nice :). But you should golf this. Commented Jun 29, 2017 at 19:51 • Sorry, this is not code golf, haven't seen this yesterday... Commented Jun 30, 2017 at 12:51 ## 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. Commented Jan 7, 2014 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") }  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 Commented Feb 19, 2011 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? Commented Feb 19, 2011 at 6:56
• @Chris well I explicitely asked the OP in the chat before answering that one.
– J B
Commented Feb 19, 2011 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 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 + ' ');});


# 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. Commented Feb 20, 2011 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
Commented Feb 19, 2011 at 20:53