Reinvent the For loop

23

6

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.

Kevin Brown

Posted 2011-02-18T23:38:28.300

Reputation: 5 756

Question was closed 2016-05-20T13:40:31.403

100 times or 1000? Or 100 000 times? – user unknown – 2011-02-19T06:50:15.483

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. – Mego – 2016-05-20T05:35:26.247

10I 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 – 2011-03-08T14:34:20.167

gotos, recursion... – Mateen Ulhaq – 2011-03-10T02:29:20.703

Answers

23

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();
}

houbysoft

Posted 2011-02-18T23:38:28.300

Reputation: 111

2A function call is a "control structure." Right? – EfForEffort – 2012-05-25T00:21:51.547

@Denis Bueno: No, a control structure is stuff like while, do, for, if... – houbysoft – 2012-05-25T01:54:40.210

1Can you please include an explanation? I got a bit lost. – Rees – 2014-01-11T15:21:54.470

You can remove that space. – S.S. Anne – 2020-02-12T23:52:34.640

1This 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 – 2014-07-17T13:59:33.850

15

Haskell, 33 chars

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

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

R. Martinho Fernandes

Posted 2011-02-18T23:38:28.300

Reputation: 2 135

1forM_ is just mapM_ with the arguments flipped, so this might be cheating. ;) – Dan Burton – 2011-03-11T05:29:26.727

12

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

Joey Adams

Posted 2011-02-18T23:38:28.300

Reputation: 9 929

11

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

Eelvex

Posted 2011-02-18T23:38:28.300

Reputation: 5 204

Without a main() in the first block, the code won't link. Therefore I think it should be included in the entry. – Nathan Osman – 2011-02-19T06:11:57.373

4@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 – 2011-02-19T15:46:51.887

1remove void then it will be 26 characters only. – Prince John Wesley – 2011-03-25T03:45:10.837

8

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

Timwi

Posted 2011-02-18T23:38:28.300

Reputation: 12 158

One might argue that the Y operator implements recursion… – Bergi – 2014-07-12T22:02:07.230

7

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>

J B

Posted 2011-02-18T23:38:28.300

Reputation: 9 638

A pity they're asked in ascending order... I'm pretty sure it would be shorter descending. – J B – 2011-02-19T00:28:20.013

@J B: Yes -- in descending order, you'd normally use the loop instruction: mov cx, 1000\nx: ... loop x – Jerry Coffin – 2011-02-20T06:47:46.680

6

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}

zzzzBov

Posted 2011-02-18T23:38:28.300

Reputation: 2 915

3function f(m,c){m&&c()&f(--m,c)} - You could make that 32 bytes :) – pimvdb – 2011-10-18T17:42:39.193

6

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 + " ")
}

Stanislav Yaglo

Posted 2011-02-18T23:38:28.300

Reputation: 141

5

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

Nemo157

Posted 2011-02-18T23:38:28.300

Reputation: 1 891

5

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);  

Justin Morgan

Posted 2011-02-18T23:38:28.300

Reputation: 556

4

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

Matt

Posted 2011-02-18T23:38:28.300

Reputation: 129

4

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.

user611

Posted 2011-02-18T23:38:28.300

Reputation:

NameError: name 'i' is not defined – J B – 2011-02-19T00:45:38.707

I've kind of fixed it. Plus, I assumed that i was predefined. – None – 2011-02-19T00:57:16.323

2If it's predefined, it's not going to change with the iteration. That's not how a for loop works. – J B – 2011-02-19T01:02:37.000

Fair point. I imagine it would need ;i=+1 after the comma. I did say it wouldn't work with all cases. – None – 2011-02-19T01:11:02.243

exec 'i=0;'+1000*'print i;i+=1;' would do the job. – flonk – 2014-01-13T13:35:42.747

3

I shall bear great shame for this, but here it is in Linux shell:

cat -An /dev/urandom|head -n1000|cut -f1

40 characters.

Ted Dziuba

Posted 2011-02-18T23:38:28.300

Reputation: 11

Prints linebreaks => disqualification! :) – user unknown – 2011-02-19T07:08:57.597

3

Here's your loop using Brainfuck, which is probably cheating:

,[.,]

user732

Posted 2011-02-18T23:38:28.300

Reputation:

:) Unfair though. – tomsmeding – 2013-12-08T21:52:31.533

2

Perl, 21 characters

map{print"$_ "}0..999

J B

Posted 2011-02-18T23:38:28.300

Reputation: 9 638

Mapping is a type of looping. Don't cheat! :-P – Chris Jester-Young – 2011-02-19T02:58:01.647

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 – 2011-02-19T06:56:03.670

@Chris well I explicitely asked the OP in the chat before answering that one. – J B – 2011-02-19T09:26:34.490

2

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.

PleaseStand

Posted 2011-02-18T23:38:28.300

Reputation: 5 369

Putting the print call inside the eval call is really clever. – Justin Morgan – 2014-01-07T22:07:48.750

2

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? :)

Ty Auvil

Posted 2011-02-18T23:38:28.300

Reputation: 473

Prints newlines as delimiters? ... print i with a space 1 ... - disqualification. :) – user unknown – 2011-02-19T07:02:28.800

1filter p{"$_ "} --- :) – Ty Auvil – 2011-02-19T16:23:22.280

I'm not sure if this should be disqualified, as it's technically (ab)using the pipeline as if it was foreach. – Iszi – 2013-12-09T15:14:41.380

2

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.

PleaseStand

Posted 2011-02-18T23:38:28.300

Reputation: 5 369

2

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.

Eelvex

Posted 2011-02-18T23:38:28.300

Reputation: 5 204

2

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.

Steve

Posted 2011-02-18T23:38:28.300

Reputation: 671

2

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")
}

Arnaud Le Blanc

Posted 2011-02-18T23:38:28.300

Reputation: 2 286

2

Clojure
(map #(print (str % " ")) (range 1 (inc 100)))

Replace print with the function to execute.
Use (inc 100) or 101 for the last value.

deiga

Posted 2011-02-18T23:38:28.300

Reputation: 101

2

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

rubber boots

Posted 2011-02-18T23:38:28.300

Reputation: 1 014

2

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?

AardvarkSoup

Posted 2011-02-18T23:38:28.300

Reputation: 344

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. – Twometer – 2017-06-29T19:51:39.837

Sorry, this is not code golf, haven't seen this yesterday... – Twometer – 2017-06-30T12:51:09.053

2

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

codeporn

Posted 2011-02-18T23:38:28.300

Reputation: 261

1

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.

B.R.

Posted 2011-02-18T23:38:28.300

Reputation: 101

Obviously never going to beat Perl, but I didn't see the Perl comment before I posted mine. – B.R. – 2011-02-19T00:07:07.627

The code uses a foreach loop, which isn't allowed in the first post. – Kevin Brown – 2011-02-19T01:32:29.167

@Bass: no it doesn't. It calls a method that happens to be called ForEach. – R. Martinho Fernandes – 2011-02-19T05:31:04.570

@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. – Joey – 2011-02-19T17:18:50.983

@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? – R. Martinho Fernandes – 2011-02-19T19:29:00.233

@Martinho: Well, that's the reason why I dislike this task. There are basically only three ways of solving it: Using an iterating primitive (keyword, function, ...), goto or recursion. And I'd understand the task so that the first kind of solution would be disallowed. It's a pretty boring task, imho :-) – Joey – 2011-02-19T23:13:31.457

@Joey: My solution uses no iterating primitive, goto or recursion.

– Timwi – 2011-03-08T17:49:27.627

This is wrong, this only prints 0 to 998. But it is also longer than necessary; Console.Write(string.Join(" ", Enumerable.Range(0, 1000))); is only 59 chars. – Timwi – 2011-03-08T20:27:09.457

1

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

user609

Posted 2011-02-18T23:38:28.300

Reputation:

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 – None – 2011-02-19T01:27:42.650

1

;; 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)))

user612

Posted 2011-02-18T23:38:28.300

Reputation:

4Please label the language used for this answer. – Nathan Osman – 2011-02-20T21:50:49.583

1

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

Eelvex

Posted 2011-02-18T23:38:28.300

Reputation: 5 204

1

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);

user619

Posted 2011-02-18T23:38:28.300

Reputation:

1

bash:

echo {1..1000}

14 chars.

user unknown

Posted 2011-02-18T23:38:28.300

Reputation: 4 210

1

Python3 - 27 chars

any(map(print,range(1000)))

gnibbler

Posted 2011-02-18T23:38:28.300

Reputation: 14 170

Cool. For the nice output: print(" ".join(map(str,range(1000)))) – Wok – 2011-02-19T20:53:28.513

1

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.

Joey

Posted 2011-02-18T23:38:28.300

Reputation: 12 260

1

sh

cat -An /dev/urandom|head -n1000|cut -f1|xargs

user741

Posted 2011-02-18T23:38:28.300

Reputation:

You can generate infinite lines with "yes". Try "yes ''|head -n1000|cat -n|xargs" – swstephe – 2014-12-22T19:42:20.093

1

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.

David Conrad

Posted 2011-02-18T23:38:28.300

Reputation: 1 037

1

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

cobbal

Posted 2011-02-18T23:38:28.300

Reputation: 131

At least it doesn't use goto. – Joey Adams – 2011-03-19T18:29:57.803

1

JavaScript, 63 characters

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

with proper console output

generalhenry

Posted 2011-02-18T23:38:28.300

Reputation: 101

1

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 + ' ');});

user920

Posted 2011-02-18T23:38:28.300

Reputation:

1

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)')

wolfhammer

Posted 2011-02-18T23:38:28.300

Reputation: 1 219

1

R - 11 characters

General case:

f(1:1000)

Where f is your function.

Specific case:

cat(1:1000)

Joel Rein

Posted 2011-02-18T23:38:28.300

Reputation: 101

1

Spaghetti PHP 44

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

enter image description here

Sammitch

Posted 2011-02-18T23:38:28.300

Reputation: 509

1

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

Isaac

Posted 2011-02-18T23:38:28.300

Reputation: 61

1

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

std''OrgnlDave

Posted 2011-02-18T23:38:28.300

Reputation: 111

1

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 :( */ })

Pebbl

Posted 2011-02-18T23:38:28.300

Reputation: 151

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.

– Gareth – 2012-11-20T09:01:29.940

@Gareth yep thanks for the quote, I assumed as much, was just a little unexpected.. and rather annoying from a codegolf point of view :) – Pebbl – 2012-11-20T09:22:06.423

0

Python 2.x - 17 chars

print range(1000)

Dominic Bou-Samra

Posted 2011-02-18T23:38:28.300

Reputation: 109

You need a for loop: print " ".join(\i` for i in range(1000))` – Wok – 2011-02-19T09:35:03.390

@wok: the challenge is to not use for-loops. – JPvdMerwe – 2011-02-20T16:26:13.053

0

Groovy, 32 bytes

(0..1000).each{ print "${it} " }

user615

Posted 2011-02-18T23:38:28.300

Reputation:

1each is foreach => disqualified :) println is printing with newline, not space => disqualified. ;) – user unknown – 2011-02-19T07:20:14.410

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. – None – 2011-02-19T14:11:03.757

0

Scala:

(1 to 100)mkString" "

21 chars not that ugly:

(1 to 100) mkString " "

user unknown

Posted 2011-02-18T23:38:28.300

Reputation: 4 210

0

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
}

Lee

Posted 2011-02-18T23:38:28.300

Reputation: 1

2And probably should fail when DEP is enabled. – Joey – 2011-02-19T17:37:05.123

Can you include the char count and language? – R. Martinho Fernandes – 2011-02-19T19:43:44.897

K, information added – Lee – 2011-02-19T21:21:26.213

0

Ti-84 Basic, 34

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

:-1>I:Lbl A:I+1>I:If I<1000:Goto A

Timtech

Posted 2011-02-18T23:38:28.300

Reputation: 12 038

0

Golf-Basic 84, 23 characters

:-1_Il`A:I++I@I<1000o`A

Timtech

Posted 2011-02-18T23:38:28.300

Reputation: 12 038

0

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)

mniip

Posted 2011-02-18T23:38:28.300

Reputation: 9 396

0

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

Ivan Genchev

Posted 2011-02-18T23:38:28.300

Reputation: 101

0

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))

Adam Speight

Posted 2011-02-18T23:38:28.300

Reputation: 1 234

0

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,' ').

criptych stands with Monica

Posted 2011-02-18T23:38:28.300

Reputation: 181

0

C - 48 characters

Compilable code.

main(int i){i^1002&&main(i+1);printf("%i",i-2);}

Oberon

Posted 2011-02-18T23:38:28.300

Reputation: 2 881

0

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

Aviel Gross

Posted 2011-02-18T23:38:28.300

Reputation: 101

0

APL (26)

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

Usage:

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

i.e.

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

prints the numbers from 1 to 100.

marinus

Posted 2011-02-18T23:38:28.300

Reputation: 30 224

0

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

Adam Speight

Posted 2011-02-18T23:38:28.300

Reputation: 1 234

0

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)

pppery

Posted 2011-02-18T23:38:28.300

Reputation: 3 987

0

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)

Daniel

Posted 2011-02-18T23:38:28.300

Reputation: 1 801

0

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.

baby-rabbit

Posted 2011-02-18T23:38:28.300

Reputation: 1 623