Loop without 'looping'

85

46

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.

CailinP

Posted 2014-07-09T12:42:59.023

Reputation: 1 061

Question was closed 2016-07-06T22:25:36.717

1What is the definition of a loop? – CousinCocaine – 2014-07-09T12:44:47.897

The bash 'yes' command would do, right? – CousinCocaine – 2014-07-09T12:45:21.127

The definition of a loop for this question will be A programming language statement which allows code to be repeatedly executed – CailinP – 2014-07-09T12:46:42.540

hmm.. shame you had to post this comment.. just noted something you didnt mention in the structures you cant use XD – Teun Pronk – 2014-07-09T12:48:27.747

I think it should be possible to copy over a lot of answers from this question.

– Martin Ender – 2014-07-09T12:51:46.783

This might sound stupid but what is the exact definition of recursion? Is that just a function calling itself? – Teun Pronk – 2014-07-09T12:53:19.233

@user24925 How sneeky and crappy can the answer be? – Teun Pronk – 2014-07-09T13:00:34.373

1Would creating new functions with the same content and then repeatedly calling them be considered recursion? What about a program compiling a program then calling that program? – SBoss – 2014-07-09T13:11:47.303

1As the existing comments and answers demonstrate, it's not clear what is covered by the "etc." in the forbidden structures. – Peter Taylor – 2014-07-09T13:43:07.447

The question has been updated for a focus on creativity. The goal here is to be creative and learn tricks that other programming languages might have (like the 'yes' command in BASH). – CailinP – 2014-07-09T13:47:52.970

@TeunPronk I added a definition of recursion to the question. It's just your basic, function calling itself definition. – CailinP – 2014-07-09T14:16:58.690

27For 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 – 2014-07-09T14:34:42.383

2"Changed to popularity contest for a focus on creativity" Changing the question is cheating! – CousinCocaine – 2014-07-09T15:12:36.990

@CousinCocaine The question and its requirements were not changed, only the winning guidelines from code golf to popularity contest. – CailinP – 2014-07-09T15:35:19.730

2@CailinP a winning answer is not a winning answer anymore. That is changing the outcome by changing the question. – CousinCocaine – 2014-07-09T15:41:19.923

1For the people who are complaining that the question is unclear, what is unclear about it? – CailinP – 2014-07-09T18:21:25.653

1Do vectorized functions count as loops? Otherwise R has this with apply – shadowtalker – 2014-07-10T02:16:03.437

4The 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 – 2014-07-10T05:59:36.347

3What 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 – 2014-07-10T06:08:45.863

What is unclear hasn't changed since my first comment: what is permitted and what is forbidden. And there's no reasonable way to fix it without posting all the permitted answers in the question, which rather defeats the object. – Peter Taylor – 2014-07-10T12:55:35.217

Please don't get hung up on what is and is not permitted. As stated above: No 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 say no to it, go ahead and do it. Many answers have already bent the rules. – CailinP – 2014-07-10T13:02:33.500

1What about a clock? Such as tty-clock -D? Or is that too lame ;) – CousinCocaine – 2014-07-11T08:53:51.417

3@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 – 2014-07-11T10:20:18.343

1I don't think that this question has an answer. Even if you don't write and exact loop or recursion, it is hidden somewhere inside. – Michal – 2014-07-14T08:04:39.507

I'm too lazy to go through all the answers... is there a crontab solution yet? – CompuChip – 2014-07-14T19:56:59.710

Answers

258

Ruby

def method_missing(meth,*args)
  puts 'Banana'
  send(meth.next)
end

def also
  puts "Orange you glad I didn't say banana?"
end

ahem

Demo

Clears its throat, prints "Banana" 3070 times, and also puts "Orange you glad I didn't say banana?".

This uses Ruby's ridiculous just-in-time method definition functionality to define every method that lies alphabetically between the words 'ahem' and 'also' ("ahem", "ahen", "aheo", "ahep", "aheq", "aher", "ahes", "ahet", "aheu", "ahev"...) to first print Banana and then call the next in the list.

histocrat

Posted 2014-07-09T12:42:59.023

Reputation: 20 600

Why does it end? – seequ – 2014-07-09T19:43:57.753

4It eventually hits "also", which is defined, and therefore not missing. – histocrat – 2014-07-09T19:45:51.610

Ah, now I see it. Somehow missed the last line. Nice one, have a plus one. – seequ – 2014-07-09T20:24:31.203

77This is hysterical. – Michael B – 2014-07-09T21:55:06.717

So it doesn't define "ahema", "ahemaa", "ahemaaa" and so on? Technically, there are infinitely many methods between "ahem" and "also"? Obviously it works, but I'm curious as to why? – barrycarter – 2014-07-09T22:18:55.893

4

@barrycarter: In Ruby, String#next, which is called in method_missing functions more or less like adding 1 to a number except it works with all alphanumeric characters (and non-alnums if they are the only characters in the string). See http://www.ruby-doc.org/core-2.1.2/String.html#method-i-next

– 3Doubloons – 2014-07-10T00:38:58.870

I don't really get the point of method_missing in Ruby; I heard about it in the Wat talk and thought was just as bad a JS's notion of addition.

– Nick T – 2014-07-10T06:17:17.183

2@NickT it is usable in classes like XML builders where you can any tag created only by b.my_tag. It also is used in ActiveRecord models or OpenStruct. In 'Wat talk' he say that global method_missing is bad, but scoped is awesome. – Hauleth – 2014-07-10T07:07:08.870

2I remember an old comment on another ruby program: "I like it because it has meth" – vidya sagar – 2014-07-11T05:35:35.053

1

same for perl: https://gist.github.com/VadimPushtaev/58216fd01d99eef22dc3

– Vadim Pushtaev – 2014-07-18T12:42:34.683

82

Python - 16

or any other language with eval.

exec"print 1;"*9

Vectorized

Posted 2014-07-09T12:42:59.023

Reputation: 3 486

Can you describe what your program does? – CailinP – 2014-07-09T13:53:38.460

10It takes a string ("print 1;"), duplicates it 9 times(*9), then executes the resulting string(exec). Repeating a chunk of code without actually looping at all. – scragar – 2014-07-09T16:46:44.907

12Yay for string multiplication! – Thane Brimhall – 2014-07-09T20:37:40.807

2Also works in Ruby if you change the exec to eval or the print to echo. – Ajedi32 – 2014-07-11T18:05:27.887

80

CSharp

I've expanded the code into a more readable fashion as this is no longer code golf and added an increment counter so that people can actually see that this program does something.

class P{
    static int x=0;
    ~P(){
        System.Console.WriteLine(++x);
        new P();
    }
    static void Main(){
        new P();
    }
}

(Don't do this ever please).

On start we create a new instance of the P class, which when the program tries to exit calls the GC which calls the finalizer which creates a new instance of the P class, which when it tries to clean up creates a new P which calls the finalizer...

The program eventually dies.

Edit: Inexplicably this runs only around 45k times before dying. I don't quite know how the GC figured out my tricky infinite loop but it did. The short is it seems it didn't figure it out and the thread just was killed after around 2 seconds of execution: https://stackoverflow.com/questions/24662454/how-does-a-garbage-collector-avoid-an-infinite-loop-here

Edit2: If you think this is a little too much like recursion consider my other solution: https://codegolf.stackexchange.com/a/33268/23300

It uses reification of generic methods so that at runtime it constantly is generating new methods and each method in term calls a newly minted method. I also avoid using reference type parameters, as normally the runtime can share the code for those methods. With a value type parameter the runtime is forced to create a new method.

Michael B

Posted 2014-07-09T12:42:59.023

Reputation: 1 551

20I didn't even know C# had destructors. +1 for teaching me. – seequ – 2014-07-09T19:48:25.510

4@TheRare, it does but they are non-deterministic in nature and may never be called during a program's execution. They are implemented as an override of the virtual method Finalize so they sometimes are called finalizer. In real C#, you should use the IDisposable pattern. – Michael B – 2014-07-09T20:05:14.720

It seems that there is a time-out that occurs at some point. I don't think it is the GC that is stopping your cycle, but instead the operating system deciding that your program is taking too long to end. – LVBen – 2014-07-09T21:38:15.300

I think this is really the runtime deciding to kill the program not necessarily the OS. The garbage collector thread called on program end is given a fixed time limit of ~2 seconds before it's killed. – Michael B – 2014-07-09T21:46:28.397

With some minor modifications (not letting the program end, releasing the the 1st P object to the GC, and repeatedly calling GC.Collect), I can get it to run indefinitely. – LVBen – 2014-07-09T21:49:37.263

I don't think it is the garbage collector deciding to stop after 2 seconds, because I can easily add a 5-second pause inside of ~P and the "destructor" still finishes as long as the Main method has not finished execution. I believe the OS/Framework sees that Main has finished executing and then decides that the program only gets 2 seconds to clean up after itself. – LVBen – 2014-07-09T22:13:49.173

Isn't this recursion, just obfuscated with the use of a destrucor? I thought about something similar using IDisposable, but that's just another way of obfuscated recursion, which is forbidden by the rules. – Num Lock – 2014-07-10T13:29:59.100

Technically it isn't. I'm not explicitly calling the ~P method. In theory, a different GC may never be invoked, it just happens to be an implementation detail that the CLR tries to call finalizers. I was thinking about IDisposable, but it really is just a sugared up try{var x=new r();...}finally{x.Dispose();}, and I thought that was too explicit. No where in my code or its compiled IL is there an explicit call to the destructor so I felt it was a little better. – Michael B – 2014-07-10T13:50:25.303

+1 for valid reason to break "don't use destructors in C# if you don't absolutely have to, as it slows down when GC calls stuff" - guideline. – Mark – 2014-07-11T09:08:36.763

I don't think that using a destructor to initialize a voodoo infinite loop is a valid reason... :P – Michael B – 2014-07-11T15:49:01.307

The same trick works in Python. My test goes by 10 millions, and still running. – Davidmh – 2014-07-14T09:00:36.010

@Davidm, Python has destructors? I didn't realize! I knew you could use the method to allow for deterministic resource release for use with the with syntax. – Michael B – 2014-07-14T13:15:20.713

@MichaelB when an object is GC, the __del__ method, if present, will be called. The behaviour is not so deterministic when you have cyclic references. – Davidmh – 2014-07-15T08:28:35.760

BTW, the program is still running... the number of iterations is so high that it doesn't even show! – Davidmh – 2014-07-15T08:29:34.627

This is still recursion, a constructor is just a method a destructor is just another method. I'm pretty sure the definition of recursion extends to chaining a couple of methods to form a loop. – Mick – 2014-07-21T05:51:21.333

This isn't C++ with deterministic destruction. Which is why the ~ are called finalizers usually in C#. No where do I explicitly or implictly call it. No where in the IL or any IR is there a call to P.Finalize virtual method. T The CLR runtime makes no guarantee that the finalizer will be called. That's why I think this 'counts'. The runtime decided because its nice to try to clean up my garbage for a while. But after 2 seconds it thinks I'm pathological and kills itself. The C++ version of this I would consider obvious recursion as if you inspect the IR there would be a call to the ~P. – Michael B – 2014-07-21T14:52:04.263

53

Befunge

.

Good old Befunge outputs 0 (from an empty stack) pretty much forever, as lines wrap around.

Le Canard fou

Posted 2014-07-09T12:42:59.023

Reputation: 711

1Ha! I love tricks like this – CailinP – 2014-07-09T22:28:05.237

47

JS

(f=function(){ console.log('hi!'); eval("("+f+")()") })()

Function fun!

A function that creates another function with the same body as itself and then runs it.

It will display hi at the end when the stack limit is reached and the entire thing collapses.

Disclaimer: you'll not be able to do anything in your browser until stack limit is reached.


And another one, more evil:

function f(){ var tab = window.open(); tab.f = f; tab.f()}()

It creates a function which opens up a window, then creates a function within that window which is copy of the function, and then runs it.

Disclaimer: if you'll allow opening of popups the only way to finish this will be to restart your computer

eithed

Posted 2014-07-09T12:42:59.023

Reputation: 1 229

5This is pretty evil for sure ;) – CailinP – 2014-07-09T18:52:13.477

28@CailinP Pretty eval for sure. – seequ – 2014-07-11T11:44:58.733

I think you're missing an f at the end of your second function. It should be }f() in the end. – Chirag Bhatia - chirag64 – 2014-07-15T07:36:08.997

@Chirag64 - it should be similar to previous example, but let's say I didn't want anybody to try it ;) – eithed – 2014-07-15T08:03:02.327

2Unfortunately, I noticed it because I tried it. :P – Chirag Bhatia - chirag64 – 2014-07-15T08:05:15.097

7-1 - this is just recursion. – user253751 – 2014-07-17T09:59:26.613

@immibis - if I'm not mistaken, in both of the examples new functions are created dynamically - so what that they have the same body as the function that spawned them? – eithed – 2014-07-17T10:11:32.573

@eithedog the second one is just recursion, AFAIK (unless tab.f = f creates a new function, which would be unexpected, but unsurprising given it's JavaScript). The first one is just trying to use a loophole - it's effectively copyFunction(f)() instead of f() – user253751 – 2014-07-18T07:45:42.503

I love that browsers, after all this time, are still so vulnerable to stuff like this – jozxyqk – 2014-07-18T15:17:33.013

@immibis - fair point, your comment got me thinking; as functions (and variables) are scoped to the window they're operating in, so the given functions should indeed be different, however the truth doesn't look too good: http://jsfiddle.net/SV6aa/. Oh well, you learn something everyday.

Everything here is a loophole - that's the point :D

– eithed – 2014-07-18T18:37:54.860

@immibis Trivial to get around it: tab.f = f.bind({}) (clones the actual function instead of the function reference, so you get an actual new function). You can go the longer way of serialising to JSON and deserialising back to a function, if you want.

– Bob – 2014-07-21T12:33:06.530

@Bob - good point, though unfortunately it would be the same trick (I guess .bind works the same way as new Function + .call(this)?) – eithed – 2014-07-21T15:49:29.083

@eithedog Similar. .call() calls the function with the new this; .bind() creates a new function with a different this value, which can then be called later - it's a completely independent function. The difference is .bind() actually creates a new function, which addresses immibis' complaint. – Bob – 2014-07-21T15:56:24.713

@Bob that's why I've written new Function + ;) – eithed – 2014-07-21T17:03:41.260

39

x86 assembly/DOS

    org 100h

start:
    mov dx,data
    mov ah,9h
    int 21h
    push start
    ret

data:
    db "Hello World!",10,13,"$"

Did I say no reversed tail recursion? Did I? madame mim purple dragons

How it works

The ret instruction, used to return from a function, actually pops the return address from the stack (which normally is put there by the corresponding call) and jumps to it. Here at each iteration we push the entrypoint address on the stack before returning, thus generating an infinite loop.

Matteo Italia

Posted 2014-07-09T12:42:59.023

Reputation: 3 669

I was wondering if this was possible in assembly. – Ian D. Scott – 2014-07-10T17:00:47.523

2Mess with the stack at your peril. Here be dragons ;-) – Digital Trauma – 2014-07-10T18:39:14.543

1

I was going to call out http://codegolf.stackexchange.com/a/34295/11259 as a dup of this one, but I see that is actually the earlier answer

– Digital Trauma – 2014-07-10T18:57:12.757

@DigitalTrauma: yep, I noticed after I posted my entry, but I got to attached to the picture of Madame Mim. :-) Fortunately there are some differences (his is a bit more obfuscated and works on 32 bit Linux, mine is played straight on DOS and has no other jump), if no one has any objection I'd leave this here anyway. – Matteo Italia – 2014-07-10T20:36:07.603

@MatteoItalia Not obfuscated, just crappy ;) (tho "add eax, 4" confused me as well, I couldn't find opcode size table so I just wild guessed size). I made it in online compiler while my work project was compiling so it looks horribly. Great idea of using "start:". – PTwr – 2014-07-10T20:51:25.197

37

Java

Straight from XKCD

Bonding

It's a never-ending game of catch between a parent and child!

The target of CHILD is set to PARENT and the target of PARENT is the CHILD. When the PARENT calls AIM, it throws the instance of the BALL class and it is caught by the catch statement. The catch statement then calls PARENT.TARGET.AIM where the target is the CHILD. The CHILD instance does the same and "throws the ball back" to the parent.

Kirk Backus

Posted 2014-07-09T12:42:59.023

Reputation: 589

3I like those comics! – Derek 朕會功夫 – 2014-07-11T05:59:43.877

1Would be better if the ball was actually being thrown between the parent and child. As-is, the ball is always thrown and caught by the same "person". – Ajedi32 – 2014-07-11T18:14:19.950

@Ajedi32 It would actually appear it does throw it back and forth; Parents TARGET is the child, and child's target is parent. Aim is called on parent, who throes the ball and has the child aim and throw the ball, cue loop – Alex Coleman – 2014-07-12T03:09:46.010

@AlexColeman Except you could completely remove the try catch statement, change TARGET.AIM(B) to TARGET.AIM(BALL), and everything would still work fine. – Ajedi32 – 2014-07-13T03:20:37.513

12@AlexColeman This code is analogous to the parent throwing the ball up in the air, catching it, then handing it to the child who does the same before handing the ball back to the parent, and so on. – Ajedi32 – 2014-07-13T03:21:38.753

@Ajedi32 Ah, I thought you meant the child never got the ball, yeah, I suppose some thrown exceptions could be added to make it more accurate – Alex Coleman – 2014-07-13T13:17:45.057

11The command TARGET.AIM(B); in method AIM is a recursive call. So this violates the "functions can not call themselves" rule. – Theodore Norvell – 2014-07-14T13:36:45.530

31

Bash, 3 characters

yes

yes will repeatedly return 'y' to the console

Edit: Everyone is encouraged to edit this line:

yes something | xargs someaction

(thanks to Olivier Dulac)

CousinCocaine

Posted 2014-07-09T12:42:59.023

Reputation: 1 572

yes is no a bash command. – philcolbourn – 2014-12-30T22:00:05.467

1Why will this keep running? im not questioning it just trying to figure out why. – Teun Pronk – 2014-07-09T13:00:18.483

2@TeunPronk yes is a bash command that prints out the word yes until it's killed or the stream becomes closed. If it's writing to the screen it'll never stop until you kill it. It's kind of cheating though, since it's a command that basically consists of a loop over printf. – scragar – 2014-07-09T13:44:05.960

1More fun would be to use yes to keep some other loop going. – trlkly – 2014-07-09T22:38:13.647

1don't forget that yes can take an argument to print something other than 'y' – Sparr – 2014-07-10T02:04:25.183

@trlkly yes | while read VAL; do ...;done - except while isn't allowed =P – Izkata – 2014-07-10T02:06:09.313

3@izkata: but then you can : yes something | xargs someaction : no recursion (you can even add -n 1 to xargs to only have 1 "something" per line, etc) . Using xargs opens the way for more complex behaviours (even ones who don't have anything at all to do with the yes output) – Olivier Dulac – 2014-07-10T13:20:38.963

4@scragar you should have just replied yes. – daviewales – 2014-07-12T04:33:37.267

The usual use of yes is to pipe it into another program that will ask a bunch of questions that you want to respond to affirmatively without any user interaction. In this case it terminates when the process it is feeding answers to closes its stdin. – Aaron Dufour – 2014-07-14T15:42:06.573

Old school denial of service: yes | write user – Ben Jackson – 2014-07-16T00:40:54.937

@BenJackson: New school denial of service: yes 'yes | write user' | parallel – CousinCocaine – 2014-07-16T07:16:25.133

Computer says no: yes no – mbatchkarov – 2014-07-18T11:22:14.183

28

C, 35 characters

main(int a,char**v){execv(v[0],v);}

The program executes itself. I'm not sure if this is considered recursion or not.

kwokkie

Posted 2014-07-09T12:42:59.023

Reputation: 301

Can you explain it a bit more? What exactly is it doing? – CailinP – 2014-07-09T13:51:22.523

execv() executes the file named by the first argument. Since v[0] is the name of this executable, it executes itself again. – kwokkie – 2014-07-09T14:08:38.033

Thanks for the explanation. Since v[0] is the name of the executable and not the name of the function, I don't think this counts as recursion. I like this! – CailinP – 2014-07-09T14:10:24.537

@CailinP It's also not recursion because it does not contain a stack. execv replaces the current process with a new one. – mniip – 2014-07-09T16:41:59.653

4@mniip Tail recursion, then, if it applied at the process level – Izkata – 2014-07-10T02:05:24.227

3@Izkata Tail recursion is still recursion, but this isn't recursion. Recursion implies a function (or process in this case) 'waiting' for another iteration of itself to terminate. In this case, exec causes the new process to replace the original one, so there's no call stack that will eventually return or overflow. – millinon – 2014-07-10T02:42:04.733

4@millinon In a language that supports the optimization, tail recursion replaces the previous call in the call stack, similar to how exec replaces the previous process. It won't overflow, either. – Izkata – 2014-07-10T03:16:00.793

@Izkata What you describe is an optimization provided by compilers, not a language feature. Tail recursion optimization allows the compiler to produce code that re-uses the stack frame, while still providing recursive behavior. You're right that tail recursion optimization is an example of recursion that can be converted to a loop fairly easily. However, since an exec call does not provide the same behavior as launching a new process and waiting for it to terminate, it is not recursive. – millinon – 2014-07-10T05:09:33.870

1@millinon just to be super pedantic and to drag out this discussion longer, in the Scheme programming language, this optimization is a language feature. It's in the spec that if you make a tail-recursive call, the interpreter/compiler has to reuse the last stack frame. This is because Scheme has no built-in looping structures, so the only way to implement a loop in Scheme is to do tail-recursion, and it would kind of suck if you got stack overflows from trying to loop too many times :) – Ord – 2014-07-11T09:53:20.827

2If you want pedantry, Scheme doesn't have "tail call optimisation", it has "proper tail calls". It is not an optimisation, it is a basic requirement of the language standard and failing to supply it is not permitted, so "optimisation" (or the suggestion that it has anything to do with recursion) is very much a discouraged term. – Leushenko – 2014-07-11T10:49:51.407

28

C (with GCC builtins - also seems to work with clang)

  • No explicit loops
  • No explicit gotos
  • No recursion
  • Just good old-fashioned messing with the stack (kids, don't try this at home without supervision):
#include <stdio.h>

void *frameloop (void *ret_addr) {
    void **fp;
    void *my_ra = __builtin_return_address(0);

    if (ret_addr) {
        fp = __builtin_frame_address(0);
        if (*fp == my_ra) return (*fp = ret_addr);
        else fp++;
        if (*fp == my_ra) return (*fp = ret_addr);
        else fp++;
        if (*fp == my_ra) return (*fp = ret_addr);
        else fp++;
        if (*fp == my_ra) return (*fp = ret_addr);
        return NULL;
    } else {
        return (my_ra);
    }
}

int main (int argc, char **argv) {
    void *ret_addr;
    int i = 0;

    ret_addr = frameloop(NULL);
    printf("Hello World %d\n", i++);
    if (i < 10) {
        frameloop(ret_addr);
    }
}

Explanation:

  • main() first calls frameloop(NULL). In this case use the __builtin_return_address() builtin to get the return address (in main()) that frameloop() will return to. We return this address.
  • printf() to show we're looping
  • now we call frameloop() with the return address for the previous call. We look through the stack for the current return address, and when we find it, we substitute the previous return address.
  • We then return from the 2nd frameloop() call. But since the return address was hacked above, we end up returning to the point in main() where the first call should return to. Thus we end up in a loop.

The search for the return address in the stack would of course be cleaner as a loop, but I unrolled a few iterations for the sake of no looping whatsoever.

Output:

$ CFLAGS=-g make frameloop
cc -g    frameloop.c   -o frameloop
$ ./frameloop 
Hello World 0
Hello World 1
Hello World 2
Hello World 3
Hello World 4
Hello World 5
Hello World 6
Hello World 7
Hello World 8
Hello World 9
$ 

Digital Trauma

Posted 2014-07-09T12:42:59.023

Reputation: 64 644

2nice! I wonder why those functions aren't part of the C spec? ;-D – Brian Minton – 2014-07-09T20:16:09.990

4

@BrianMinton Actually a similar thing should be achievable with setjmp()/longjmp(). These aren't in the c standard, but are in the standard library. I felt like munging the stack manually today though ;-)

– Digital Trauma – 2014-07-09T20:35:53.060

@BrianMinton My guess is because it is in CPU specs, which makes it (hardware) platform dependent. And it is rather dangerous to use when stackframe is auto-generated, I would not be surprised if AV would cry about such code. Check this or this for x86 asm versions.

– PTwr – 2014-07-11T07:01:32.297

27

Haskell

The following code contains no recursive function (even indirectly), no looping primitive and doesn't call any built-in recursive function (uses only IO's output and binding), yet it repeats a given action idenfinitely:

data Strange a = C (Strange a -> a)

-- Extract a value out of 'Strange'
extract :: Strange a -> a
extract (x@(C x')) = x' x

-- The Y combinator, which allows to express arbitrary recursion
yc :: (a -> a) -> a
yc f =  let fxx = C (\x -> f (extract x))
        in extract fxx

main = yc (putStrLn "Hello world" >>)

Function extract doesn't call anything, yc calls just extract and main calls just yc and putStrLn and >>, which aren't recursive.

Explanation: The trick is in the recursive data type Strange. It is a recursive data type that consumes itself, which, as shown in the example, allows arbitrary repetition. First, we can construct extract x, which essentially expresses self-application x x in the untyped lambda calculus. And this allows to construct the Y combinator defined as λf.(λx.f(xx))(λx.f(xx)).


Update: As suggested, I'm posting a variant that is closer to the definition of Y in the untyped lambda calculus:

data Strange a = C (Strange a -> a)

-- | Apply one term to another, removing the constructor.
(#) :: Strange a -> Strange a -> a
(C f) # x = f x
infixl 3 #

-- The Y combinator, which allows to express arbitrary recursion
yc :: (a -> a) -> a
yc f =  C (\x -> f (x # x)) # C (\x -> f (x # x))

main = yc (putStrLn "Hello world" >>)

Petr Pudlák

Posted 2014-07-09T12:42:59.023

Reputation: 4 272

3Recursive data structures instead of recursive functions... nice. – ApproachingDarknessFish – 2014-07-11T00:23:27.033

6this one is close to my heart being someone who is interested in total functional programing. You just showed how to make the Y-combinator with a negatively recurring data type. This is why total languages require recurring types occur to the right of the arrow and why rose trees are disallowed. Nice one! I made an account here just to upvote this! – Jake – 2014-07-14T04:45:05.133

You could remove the let binding and define yc f = extract $ C $ f.extract, since let binding arguably a language feature that allows recursion (the classical let x = x in x). This also reduces some chars :) – Earth Engine – 2014-07-16T03:01:09.050

or even yc = extract . C . (.extract) – Earth Engine – 2014-07-16T03:05:50.860

@EarthEngine True, I just wanted to keep the structure closer to the original definition of Y. – Petr Pudlák – 2014-07-16T05:34:03.623

@PetrPudlák Then I think you should consider lambda expression. 1) the original Y combinator is expressed in lambda calculus, 2) lambda expression does not allow recursion directly so it is a better suit for the rules. – Earth Engine – 2014-07-16T05:44:51.160

+1 Until I read this, I had thought that Y and Z are inexpressible in Haskell. – Theodore Norvell – 2014-07-17T19:05:32.317

@TheodoreNorvell One way how to view the trick is that the data type provides a way around the type system to avoid self-application. The data type serves as a bridge between a type t and t -> t, which then allows to apply a value of t to itself. (The minor difference is that we have have here Strange a ~ Strange a -> a so that we can get a value of type a at the end.) – Petr Pudlák – 2014-07-17T19:48:10.880

corecursion, the dual to recursion. – FUZxxl – 2014-09-26T22:58:03.263

26

C++

The following outputs a countdown from 10 to "Blast off!" using template metaprogramming.

#include <iostream>

template<int N>
void countdown() {
    std::cout << "T minus " << N << std::endl;
    countdown<N-1>();
}

template<>
void countdown<0>() {
    std::cout << "Blast off!" << std::endl;
}

int main()
{
    countdown<10>();
    return 0;
}

It might look like a classic example of recursion, but it actually isn't, at least technically, depending on your definition. The compiler will generate ten different functions. countdown<10> prints "T minus 10" and then calls countdown<9>, and so on down to countdown<0>, which prints "Blast off!" and then returns. The recursion happens when you compile the code, but the executable doesn't contain any looping structures.

In C++11 one can achieve similar effects using the constexpr keyword, such as this factorial function. (It's not possible to implement the countdown example this way, since constexpr functions can't have side-effects, but I think it might be possible in the upcoming C++14.)

constexpr int factorial(int n)
{
    return n <= 1 ? 1 : (n * factorial(n-1));
}

Again this really looks like recursion, but the compiler will expand out factorial(10) into 10*9*8*7*6*5*4*3*2*1, and then probably replace it with a constant value of 3628800, so the executable will not contain any looping or recursive code.

Nathaniel

Posted 2014-07-09T12:42:59.023

Reputation: 6 641

4The second one of these really is pure and simple recursion, not metaprogramming. Firstly because the compiler will (in the general case) emit a regular function body for you to use with non-constant arguments; and secondly because when it does perform a compile-time operation, it doesn't do any of that template-style "expansion" stuff, it runs a standard in-place evaluation - the same as the runtime one - to produce 3628800 directly without an intermediate form. – Leushenko – 2014-07-11T11:23:37.860

@Leushenko yeah I know. But then again the template example example does the same thing - uses a recursive function in a Turing-complete language at compile-time - the only difference is that the constexpr one uses a language that looks much more like C++. As with all the answers this one bends the rules, and I'm just being honest about it. constexpr was specifically designed to make (some aspects of) template metaprogramming obsolete, so it definitely seems worth mentioning in a post on the subject. – Nathaniel – 2014-07-11T12:59:41.337

1+1: &countdown<N-1> != &countdown<N>. – Thomas Eding – 2014-07-18T07:33:19.147

21

Java

Let's play with Java class loader and set it as its own parent:

import java.lang.reflect.Field;

public class Loop {
    public static void main(String[] args) throws Exception {
        System.out.println("Let's loop");
        Field field = ClassLoader.class.getDeclaredField("parent");
        field.setAccessible(true);
        field.set(Loop.class.getClassLoader(), Loop.class.getClassLoader());

    }
}

This loop is actually so strong you'll have to use a kill -9 to stop it :-)

It uses 100,1% of my Mac's CPU.

100,1% of CPU

You can try to move the System.out at the end of the main function to experiment an alternate funny behavior.

Arnaud

Posted 2014-07-09T12:42:59.023

Reputation: 8 231

lol. getting java stuck in itself :) – masterX244 – 2014-07-12T21:29:58.400

Love the JVM recursive loading hack. – Isiah Meadows – 2014-07-13T07:32:37.013

20

CSharp

One more and equally wicked::

public class P{

    class A<B>{
        public static int C<T>(){
            System.Console.WriteLine(typeof(T));
            return C<A<T>>();
        }
    }
    public static void Main(){
        A<P>.C<int>();
    }
}

This is not recursion... this is reification of code templates. While it appears we are calling the same method, the runtime is constantly creating new methods. We use the type parameter of int, as this actually forces it to create an entire new type and each instance of the method has to jit a new method. It cannot code share here. Eventually, we kill the call stack as it waits infinitely for the return of int that we promised but never delivered. In a similar fashion, we keep writing the type we created to keep it interesting. Basically each C we call is an enitrely new method that just has the same body. This is not really possible in a language like C++ or D that do their templates at compile time. Since, C# JIT is super lazy it only creates this stuff at the last possible moment. Thus, this is another fun way to get csharp to keep calling the same code over and over and over...

Michael B

Posted 2014-07-09T12:42:59.023

Reputation: 1 551

14

Dart

I guess this would be the classical way of doing recursion without any actual recursive function. No function below refers to itself by name, directly or indirectly.

(Try it at dartpad.dartlang.org)

// Strict fixpoint operator.
fix(f) => ((x)=>f(x(x))) ((x)=>(v)=>f(x(x))(v));
// Repeat action while it returns true.
void repeat(action) { fix((rep1) => (b) { if (b()) rep1(b); })(action); }

main() {
  int x = 0;
  repeat(() {  
    print(++x);
    return x < 10;
  });
}

lrn

Posted 2014-07-09T12:42:59.023

Reputation: 521

6The Y combinator? – aditsu quit because SE is EVIL – 2014-07-09T17:53:19.297

5Technically, I guess it's the Z combinator because it's for a strict language. The Y combinator requires a lazy language to avoid infinite unfolding. The only difference is that the latter part of it is eta-expanded. – lrn – 2014-07-10T05:56:23.283

14

Redcode 94 (Core War)

MOV 0, 1

Copies instruction at address zero to address one. Because in Core War all addresses are relative to current PC address and modulo the size of the core, this is an infinite loop in one, non-jump, instruction.

This program (warrior) is called "Imp" and was first published by AK Dewdney.

wberry

Posted 2014-07-09T12:42:59.023

Reputation: 281

Nice, I was hoping this hadn't been posted yet. +1 – mbomb007 – 2015-09-10T19:09:12.293

3Imps shall march, ready your gates, ready them or you'll be crushed. – seequ – 2014-07-10T22:54:22.553

Ready your SPL 0, 0; MOV 1, -2 indeed. – wberry – 2014-07-13T21:42:48.693

12

JS

Not very original but small. 20 chars.

setInterval(alert,1)

xem

Posted 2014-07-09T12:42:59.023

Reputation: 5 523

You can actually remove ,1 and it will still works, – Derek 朕會功夫 – 2014-07-11T05:59:03.570

@Derek朕會功夫 if I do that, I only get one alert on Firefox – xem – 2014-07-11T08:22:40.297

One might discuss if setInterval isn't a loop. It loops 'alert', every 1ms, until clearInterval – Martijn – 2014-07-11T08:45:03.083

1In chrome it works without the last parameter. The code should be counted as valid if it works in at least one environment. – Derek 朕會功夫 – 2014-07-11T15:55:01.327

Although using setInterval is actually against the " You cannot use a programming language statement which allows code to be repeatedly executed" rule. – Derek 朕會功夫 – 2014-07-11T15:58:15.907

3@Derek朕會功夫 setInterval is not a statement, though; it's only a function. It's used inside an expression statement, and if we can't use expression statements, then I just don't even know anymore. – Keen – 2014-07-11T21:17:27.297

1@Cory - Well I guess that's valid then! – Derek 朕會功夫 – 2014-07-12T00:55:35.540

12

Signals in C

#include <stdio.h>
#include <signal.h>

int main(void) {
    signal(SIGSEGV, main);
    *(int*)printf("Hello, world!\n") = 0;
    return 0;
}

The behaviour of this program is obviously very much undefined, but today, on my computer, it keeps printing "Hello, world!".

Thomas Padron-McCarthy

Posted 2014-07-09T12:42:59.023

Reputation: 501

11

Emacs Lisp

This is a great time to show off Lisp's powerful design where "code is data and data is code". Granted, these examples are very inefficient and this should never be used in a real context.

The macros generate code that is an unrolled version of the supposed loop and that generated code is what is evaluated at runtime.

repeat-it: allows you to loop N times

(defmacro repeat-it (n &rest body)
  "Evaluate BODY N number of times.
Returns the result of the last evaluation of the last expression in BODY."
  (declare (indent defun))
  (cons 'progn (make-list n (cons 'progn body))))

repeat-it test:

;; repeat-it test
(progn
  (setq foobar 1)

  (repeat-it 10
    (setq foobar (1+ foobar)))

  ;; assert that we incremented foobar n times
  (assert (= foobar 11)))

repeat-it-with-index:

This macro is like repeat-it but it actually works just like the common looping macro do-times it allows you to specify a symbol that will be bound to the loop index. It uses an expansion time symbol to ensure that the index variable is set correctly at the beginning of each loop regardless of whether or not you modify it's value during the loop body.

(defmacro repeat-it-with-index (var-and-n &rest body)
  "Evaluate BODY N number of times with VAR bound to successive integers from 0 inclusive to n exclusive..
VAR-AND-N should be in the form (VAR N).
Returns the result of the last evaluation of the last expression in BODY."
  (declare (indent defun))
  (let ((fallback-sym (make-symbol "fallback")))
    `(let ((,(first var-and-n) 0)
           (,fallback-sym 0))
       ,(cons 'progn
              (make-list (second var-and-n)
                         `(progn
                            (setq ,(first var-and-n) ,fallback-sym)
                            ,@body
                            (incf ,fallback-sym)))))))

repeat-it-with-index test:

This test shows that:

  1. The body does evaluate N times

  2. the index variable is always set correctly at the beginning of each iteration

  3. changing the value of a symbol named "fallback" won't mess with the index

;; repeat-it-with-index test
(progn
  ;; first expected index is 0
  (setq expected-index 0)

  ;; start repeating
  (repeat-it-with-index (index 50)
    ;; change the value of a  'fallback' symbol
    (setq fallback (random 10000))
    ;; assert that index is set correctly, and that the changes to
    ;; fallback has no affect on its value
    (assert (= index expected-index))
    ;; change the value of index
    (setq index (+ 100 (random 1000)))
    ;; assert that it has changed
    (assert (not (= index expected-index)))
    ;; increment the expected value
    (incf expected-index))

  ;; assert that the final expected value is n
  (assert (= expected-index 50)))

Jordon Biondo

Posted 2014-07-09T12:42:59.023

Reputation: 1 030

11

Untyped lambda calculus

λf.(λx.f (x x)) (λx.f (x x))

Arthur B

Posted 2014-07-09T12:42:59.023

Reputation: 310

IMHO, lambda calculus is a model of computation and is not a programming language (i.e. without a concrete machine model, we cannot consider lambda calculus as a PL). – Ta Thanh Dinh – 2016-03-13T02:31:56.583

You can absolutely build a machine that interprets lambda calculus. And the syntax can be used as a programming language. See for instance https://github.com/MaiaVictor/caramel

– Arthur B – 2016-03-13T02:41:03.640

3I'm not sure if this counts as recursion or not, what with being the fundamental theoretical basis for it... +1 anyway. – fluffy – 2014-07-12T18:17:54.063

@fluffy It's not recursive itself, none of the functions call themselves (particularly because functions are not named). – proud haskeller – 2014-08-11T16:57:52.380

10

Haskell, 24 characters

sequence_ (repeat (print "abc"))

or in a condensed form, with 24 characters

sequence_$repeat$print"" 

(although the text is changed, this will still loop - this will print two quotes and a newline infinitely)

explanation: print "abc" is basically an i/o action that just prints "abc".
repeat is a function which takes a value x and returns an infinite list made of only x.
sequence_ is a function that takes a list of i/o actions and returns an i/o action that does all of the actions sequentially.

so, basically, this program makes an infinite list of print "abc" commands, and repeatedly executes them. with no loops or recursion.

proud haskeller

Posted 2014-07-09T12:42:59.023

Reputation: 5 866

4I was going to post basically the same answer in Clojure, but I thought repeat would be a programming language statement which allows code to be repeatedly executed. – seequ – 2014-07-09T16:04:34.853

3fix(print"">>), this also involves no explicitly named repetition functions. – mniip – 2014-07-09T16:47:54.493

1@TheRare I don't know how is is in closure, but in Haskell repeat isn't "a programming language statement which allows code to be repeatedly executed" - it is a function that generates infinite lists. it's a loop just as "int[] arr = {x,x,x};" is a loop. – proud haskeller – 2014-07-09T17:54:52.200

@mniip great on the character count, i wouldn't succeed making it so short myself. but, on the other hand, fix is a recursion contaminator - this is a "language construct" meant entirely for recursion. maybe you should post this as an answer. – proud haskeller – 2014-07-09T17:56:24.890

@proudhaskeller It's the same in clojure. – seequ – 2014-07-09T18:31:45.963

@proudhaskeller I fail to see how it is a language construct and how it is meant entirely for recursion. – mniip – 2014-07-09T22:05:40.970

Well then, post it if you want to – proud haskeller – 2014-07-10T04:14:27.560

@proudhaskeller: But sequence_ is defined using recursion? – Bergi – 2014-07-10T18:26:31.190

1yes, but something must be implemented using recursion, because without it it's basically impossible – proud haskeller – 2014-07-10T19:23:45.000

3Actually, every function there is in this code is defined using recursion - even print – proud haskeller – 2014-07-10T19:27:10.263

Did you really need repeat? You could have generated an infinite list without it too? Did you consider using cycle instead? – devnull – 2014-07-12T15:43:04.463

10

ASM (x86 + I/O for Linux)

It does not matter how much your puny high level languages will struggle, it will still be just hidden instruction pointer manipulation. In the end it will be some sort of "goto" (jmp), unless you are bored enough to unroll loop in runtime.

You can test code on Ideone

You can also check out more refined version of this idea in Matteo Italia DOS code.

It starts with string of 0..9 and replaces it with A..J, no direct jumps used (so lets say that no "goto" happened), no recurrence either.

Code probably could be smaller with some abuse of address calculation, but working on online compiler is bothersome so I will leave it as it is.

Core part:

mov dl, 'A' ; I refuse to explain this line!
mov ebx, msg ; output array (string)

call rawr   ; lets put address of "rawr" line on stack
rawr: pop eax ; and to variable with it! In same time we are breaking "ret"

add eax, 4 ; pop eax takes 4 bytes of memory, so for sake of stack lets skip it
mov [ebx], dl ; write letter
inc dl ; and proceed to next 
inc ebx
cmp dl, 'J' ; if we are done, simulate return/break by leaving this dangerous area
jg print

push eax ; and now lets abuse "ret" by making "call" by hand
ret

Whole code

section     .text
global      _start                              

_start:

;<core>
mov dl, 'A'
mov ebx, msg

call rawr
rawr: pop eax

add eax, 4
mov [ebx], dl
inc dl
inc ebx
cmp dl, 'J'
jg print

push eax
ret
;</core>

; just some Console.Write()
print:
    mov     edx,len
    mov     ecx,msg
    mov     ebx,1
    mov     eax,4
    int     0x80

    mov     eax,1
    xor     ebx, ebx
    int     0x80

section     .data

msg     db  '0123456789',0xa
len     equ $ - msg

PTwr

Posted 2014-07-09T12:42:59.023

Reputation: 201

I was going to call this out as a dup of http://codegolf.stackexchange.com/a/34298/11259, but I see this is the earlier answer. +1

– Digital Trauma – 2014-07-10T18:56:34.857

@DigitalTrauma oh, I see someone made refined version of my idea - old trick, but in era of managed code people tend to forgot how things truly work. (I dislike golfing, way too often it is reduced to "look mom! I can make stuff happen by pressing one key!") – PTwr – 2014-07-10T20:45:13.943

9

C Preprocessor

A little "technique" that I came up with during an obfuscation challenge. There's no function recursion, but there is... file recursion?

noloop.c:

#if __INCLUDE_LEVEL__ == 0
int main() 
{
    puts("There is no loop...");
#endif
#if __INCLUDE_LEVEL__ <= 16
    puts(".. but Im in ur loop!");
    #include "noloop.c"
#else
    return 0;
}
#endif

I wrote/tested this using gcc. Obviously your compiler needs to support the __INCLUDE_LEVEL__ macro (or alternatively the __COUNTER__ macro with some tweaking) in order for this to compile. It should be fairly obvious how this works, but for fun, run the preprocessor without compiling the code (use the -E flag with gcc).

ApproachingDarknessFish

Posted 2014-07-09T12:42:59.023

Reputation: 951

8

PHP

Here's one with PHP. Loops by including the same file until counter reaches $max:

<?php
if (!isset($i))
    $i = 0;        // Initialize $i with 0
$max = 10;         // Target value

// Loop body here
echo "Iteration $i <br>\n";

$i++;               // Increase $i by one on every iteration

if ($i == $max)
    die('done');    // When $i reaches $max, end the script
include(__FILE__);  // Proceed with the loop
?>

The same as a for-loop:

<?php
for ($i = 0; $i < 10; $i++) {
    echo "Iteration $i <br>\n";
}
die('done');
?>

Pichan

Posted 2014-07-09T12:42:59.023

Reputation: 241

Is header("Location: .?x=".$_GET['x']+1); counted as recursion? – Charlie – 2015-09-16T21:42:45.183

Darn, this counts as recursion as well, doesn't it? – Pichan – 2014-07-09T22:40:13.737

Don't think it is - the similarity comes to mind of @Nathaniel's example: the preprocessor will include these files which are then evaluated simultaneously. – eithed – 2014-07-10T09:36:47.897

@Pichan I would say it is more of loop unfolding, as you end with copies of code in memory. – PTwr – 2014-07-11T07:04:13.440

I just saw the question today and came up with almost identical code. Too late for me! – TecBrat – 2014-07-15T14:47:35.443

8

Python

The following code contains no recursive function (directly or indirect), no looping primitive and doesn't call any built-in function (except print):

def z(f):
    g = lambda x: lambda w: f(lambda v: (x(x))(v), w)
    return g(g)

if __name__ == "__main__":
    def msg(rec, n):
        if (n > 0):
            print "Hello world!"
            rec(n - 1)
    z(msg)(7)

Prints "Hello world!" a given number of times.

Explanation: Function z implements the strict Z fixed-point combinator, which (while not recursively defined) allows to express any recursive algorithm.

Petr Pudlák

Posted 2014-07-09T12:42:59.023

Reputation: 4 272

I would call g very much indirectly recursive. – seequ – 2014-07-10T16:11:40.390

@TheRare Why? What is your argument? What does g call that calls g again? Of course that the trick is the self-application g(g), but there is no recursion involved. Would you indeed call g indirectly recursive if you haven't seen g(g)? This is the standard way how to do it in languages that don't allow recursive definitions, such as the lambda calculus. – Petr Pudlák – 2014-07-10T16:46:51.020

You give g as argument x and then call x(x). – seequ – 2014-07-10T16:49:16.867

2@TheRare A function (or a set of functions) isn't recursive or non-recursive by how it's used, this is determined just by its definition. – Petr Pudlák – 2014-07-10T17:05:04.107

1all of the answers cheat in one way or another: there's always recursion or a loop somewhere, if not in the answer, then in code the answer invokes. I like the way this one cheats. – Wayne Conrad – 2014-07-11T14:47:50.033

8

Perl-regex

(q x x x 10) =~ /(?{ print "hello\n" })(?!)/;

demo

or try it as:

perl -e '(q x x x 10) =~ /(?{ print "hello\n" })(?!)/;'

The (?!) never match. So the regex engine tries to match each zero width positions in the matched string.

The (q x x x 10) is the same as (" " x 10) - repeat the space ten times.

Edit: changed the "characters" to zero width positions to be more precise for better understandability. See answers to this stackoverflow question.

jm666

Posted 2014-07-09T12:42:59.023

Reputation: 191

8

z80 machine code

In an environment where you can execute at every address and map ROM everywhere, map 64kb of ROM filled with zeroes to the entire address space.

What it does: nothing. Repeatedly.

How it works: the processor will start executing, the byte 00 is a nop instruction, so it will just continue on, reach the address $ffff, wrap around to $0000, and continue executing nops until you reset it.

To make it do slightly more interesting, fill the memory with some other value (be careful to avoid control flow instructions).

harold

Posted 2014-07-09T12:42:59.023

Reputation: 1 199

You could fill the memory with zeroes, and place a real program in there somewhere. – seequ – 2014-07-12T10:23:59.887

So you could put in a 64k program, with no branching whatsoever, and it would just repeatedly execute? – Bill Woodger – 2014-07-12T12:26:10.037

@BillWoodger you could, especially if you have no interrupts on the platform (or none enabled) – harold – 2014-07-12T12:59:27.000

Kind of fun :-) – Bill Woodger – 2014-07-12T14:31:51.350

6

T-SQL -12

print 1
GO 9

Actually more of a quirk of Sql Server Management Studio. GO is a script separator and is not part of the T-SQL language. If you specify GO followed by a number it will execute the block that many times.

Michael B

Posted 2014-07-09T12:42:59.023

Reputation: 1 551

1I use T-SQL almost everyday and had no idea that you could do this with GO. +1 – CailinP – 2014-07-11T00:32:16.333

Technically, that's not T-SQL. GO is actually an SSMS directive, which is why you cannot put it in T-SQL scripted objects, like say a stored procedure. – RBarryYoung – 2014-07-21T12:54:29.930

Yeah, I added that in my spoiler comment. I would figure using sqlcmd would be too much cheating. – Michael B – 2014-07-21T14:53:39.780

6

C#

Prints out all integers from uint.MaxValue to 0.

   class Program
   {
      public static void Main()
      {
          uint max = uint.MaxValue;
          SuperWriteLine(ref max);
          Console.WriteLine(0);
      }

      static void SuperWriteLine(ref uint num)
      {
          if ((num & (1 << 31)) > 0) { WriteLine32(ref num); }
          if ((num & (1 << 30)) > 0) { WriteLine31(ref num); }
          if ((num & (1 << 29)) > 0) { WriteLine30(ref num); }
          if ((num & (1 << 28)) > 0) { WriteLine29(ref num); }
          if ((num & (1 << 27)) > 0) { WriteLine28(ref num); }
          if ((num & (1 << 26)) > 0) { WriteLine27(ref num); }
          if ((num & (1 << 25)) > 0) { WriteLine26(ref num); }
          if ((num & (1 << 24)) > 0) { WriteLine25(ref num); }
          if ((num & (1 << 23)) > 0) { WriteLine24(ref num); }
          if ((num & (1 << 22)) > 0) { WriteLine23(ref num); }
          if ((num & (1 << 21)) > 0) { WriteLine22(ref num); }
          if ((num & (1 << 20)) > 0) { WriteLine21(ref num); }
          if ((num & (1 << 19)) > 0) { WriteLine20(ref num); }
          if ((num & (1 << 18)) > 0) { WriteLine19(ref num); }
          if ((num & (1 << 17)) > 0) { WriteLine18(ref num); }
          if ((num & (1 << 16)) > 0) { WriteLine17(ref num); }
          if ((num & (1 << 15)) > 0) { WriteLine16(ref num); }
          if ((num & (1 << 14)) > 0) { WriteLine15(ref num); }
          if ((num & (1 << 13)) > 0) { WriteLine14(ref num); }
          if ((num & (1 << 12)) > 0) { WriteLine13(ref num); }
          if ((num & (1 << 11)) > 0) { WriteLine12(ref num); }
          if ((num & (1 << 10)) > 0) { WriteLine11(ref num); }
          if ((num & (1 << 9)) > 0) { WriteLine10(ref num); }
          if ((num & (1 << 8)) > 0) { WriteLine09(ref num); }
          if ((num & (1 << 7)) > 0) { WriteLine08(ref num); }
          if ((num & (1 << 6)) > 0) { WriteLine07(ref num); }
          if ((num & (1 << 5)) > 0) { WriteLine06(ref num); }
          if ((num & (1 << 4)) > 0) { WriteLine05(ref num); }
          if ((num & (1 << 3)) > 0) { WriteLine04(ref num); }
          if ((num & (1 << 2)) > 0) { WriteLine03(ref num); }
          if ((num & (1 <<  1)) > 0) { WriteLine02(ref num); }
          if ((num & (1 <<  0)) > 0) { WriteLine01(ref num); }
      }

      private static void WriteLine32(ref uint num) { WriteLine31(ref num); WriteLine31(ref num); }
      private static void WriteLine31(ref uint num) { WriteLine30(ref num); WriteLine30(ref num); }
      private static void WriteLine30(ref uint num) { WriteLine29(ref num); WriteLine29(ref num); }
      private static void WriteLine29(ref uint num) { WriteLine28(ref num); WriteLine28(ref num); }
      private static void WriteLine28(ref uint num) { WriteLine27(ref num); WriteLine27(ref num); }
      private static void WriteLine27(ref uint num) { WriteLine26(ref num); WriteLine26(ref num); }
      private static void WriteLine26(ref uint num) { WriteLine25(ref num); WriteLine25(ref num); }
      private static void WriteLine25(ref uint num) { WriteLine24(ref num); WriteLine24(ref num); }
      private static void WriteLine24(ref uint num) { WriteLine23(ref num); WriteLine23(ref num); }
      private static void WriteLine23(ref uint num) { WriteLine22(ref num); WriteLine22(ref num); }
      private static void WriteLine22(ref uint num) { WriteLine21(ref num); WriteLine21(ref num); }
      private static void WriteLine21(ref uint num) { WriteLine20(ref num); WriteLine20(ref num); }
      private static void WriteLine20(ref uint num) { WriteLine19(ref num); WriteLine19(ref num); }
      private static void WriteLine19(ref uint num) { WriteLine18(ref num); WriteLine18(ref num); }
      private static void WriteLine18(ref uint num) { WriteLine17(ref num); WriteLine17(ref num); }
      private static void WriteLine17(ref uint num) { WriteLine16(ref num); WriteLine16(ref num); }
      private static void WriteLine16(ref uint num) { WriteLine15(ref num); WriteLine15(ref num); }
      private static void WriteLine15(ref uint num) { WriteLine14(ref num); WriteLine14(ref num); }
      private static void WriteLine14(ref uint num) { WriteLine13(ref num); WriteLine13(ref num); }
      private static void WriteLine13(ref uint num) { WriteLine12(ref num); WriteLine12(ref num); }
      private static void WriteLine12(ref uint num) { WriteLine11(ref num); WriteLine11(ref num); }
      private static void WriteLine11(ref uint num) { WriteLine10(ref num); WriteLine10(ref num); }
      private static void WriteLine10(ref uint num) { WriteLine09(ref num); WriteLine09(ref num); }
      private static void WriteLine09(ref uint num) { WriteLine08(ref num); WriteLine08(ref num); }
      private static void WriteLine08(ref uint num) { WriteLine07(ref num); WriteLine07(ref num); }
      private static void WriteLine07(ref uint num) { WriteLine06(ref num); WriteLine06(ref num); }
      private static void WriteLine06(ref uint num) { WriteLine05(ref num); WriteLine05(ref num); }
      private static void WriteLine05(ref uint num) { WriteLine04(ref num); WriteLine04(ref num); }
      private static void WriteLine04(ref uint num) { WriteLine03(ref num); WriteLine03(ref num); }
      private static void WriteLine03(ref uint num) { WriteLine02(ref num); WriteLine02(ref num); }
      private static void WriteLine02(ref uint num) { WriteLine01(ref num); WriteLine01(ref num); }
      private static void WriteLine01(ref uint num) { Console.WriteLine(num--); }
   }

LVBen

Posted 2014-07-09T12:42:59.023

Reputation: 290

1I don't really know if this counts. You are explicitly calling WriteLine01 Int.MaxValue times. It just exploded behind a massive amount of callstack. – Michael B – 2014-07-09T20:57:11.560

How does it not count? There is no loop and no recursion. – LVBen – 2014-07-09T21:00:51.280

1Also, the call stack is not anywhere near massive unless maybe you consider a 32 calls high to be massive. – LVBen – 2014-07-09T21:02:37.260

Why not just call Console.WriteLine(n) 32 times? – David Carpenter – 2014-07-12T15:28:35.653

1Why only 32 times instead of 4294967296 times? – LVBen – 2014-07-12T19:53:30.187

Please, do not ever contribute code like this in an open source project. – ja72 – 2014-07-12T22:32:23.517

4@ja72 If I'm ever working on an open source project in which I cannot use loops or recursion, then I am totally going to contribute code like this! – LVBen – 2014-07-13T00:28:58.717

6

JS (in browser)

How about this?

document.write(new Date());
location = location;

Prints the current time and reloads the page.

Pichan

Posted 2014-07-09T12:42:59.023

Reputation: 241

Oh shoot. I just posted an answer with the same basic concept. I had been scanning the page for "JavaScript" or anything showing HTML tags. I suppose I might leave my answer up, just because it handles the corner-case where the location contains a "#". Anyway, +1. – Keen – 2014-07-11T21:36:03.667

In Firefox 30: [Exception... "The operation is insecure." code: "18" nsresult: "0x80530012 (SecurityError)" location: "<unknown>"] – Alex Reynolds – 2014-07-20T11:48:03.883

@AlexReynolds Huh, weird. Mine works just fine on FF 30. – Pichan – 2014-07-21T00:07:27.563

I only copied and pasted in your code as it was written. It doesn't work. Perhaps you have some special security preferences enabled to make this work? – Alex Reynolds – 2014-07-21T04:52:18.240

@AlexReynolds Nope, never changed any security settings. And it works on Chrome too. – Pichan – 2014-07-24T20:33:48.790

5

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

fluffy

Posted 2014-07-09T12:42:59.023

Reputation: 725

1FYI, 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 – 2014-07-13T22:11:41.690

@Joshua Oops, good catch. – fluffy – 2014-07-13T22:23:33.097

Skirting the edge of 'goto' but I reckon it counts. – Alchymist – 2014-07-14T22:37:00.090

@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 – 2014-07-14T22:45:45.487

4

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.

Petr Pudlák

Posted 2014-07-09T12:42:59.023

Reputation: 4 272

4

JS

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

(function(){
    document.body.innerHTML = '<input id="b" type="button" value="$$$ CLICK TO EARN MONEY $$$" onmouseover="repeat()" style="top:0px; color:red; font-size:32px; position:absolute; background:yellow;"></div>'
    var style = document.getElementById("b").style;
    var top = true;
    window.repeat = function(){
        console.log("repeat !");

        style.color = top ? "purple" : "red";
        style.background = top ? "cyan" : "yellow";
        style.top = ( (Math.random()*100) + (top?200:0) )+"px";
        style.left = (Math.random()*200)+"px";
        top = !top;
    }
})();

You can test it by pasting this code in the JS console of your browser.

Yann

Posted 2014-07-09T12:42:59.023

Reputation: 141

Funniest one yet – Sergey Telshevsky – 2014-07-15T12:35:42.993

3

C: 42

int f(){g();}int g(){f();}int main(){f();}

main calls f and f calls g & g calls f. Pretty sure that's not the defined recursion.

If you wanted a bit more loop control (i.e., not an infinite loop), you'll have to add int i in a few places and add some check to stop:

C: 75

int f(int i){if(i>99) return;g(++i);}int g(int i){f(++i);}int main(){f(0);}

Kyle Kanos

Posted 2014-07-09T12:42:59.023

Reputation: 4 270

It's still recursive, you're just doing it with two alternate layers. – scragar – 2014-07-09T16:44:44.690

4@scragar: OP defined a recursive function as a function that calls itself, neither f nor g calls itself. – Kyle Kanos – 2014-07-09T16:46:10.713

3The term for this is 'mutual recursion'. – user19057 – 2014-07-09T22:00:26.060

The first solution doesn't compile. You have to forward declare g() (and in the second too). – clcto – 2014-07-09T22:38:16.577

@clcto: works fine for me. What compiler are you using? – Kyle Kanos – 2014-07-09T22:51:11.367

@KyleKanos I was just using ideone: http://ideone.com/o3zzMB (I changed the return type to void just to get rid of the warnings "did not return a value")

– clcto – 2014-07-10T00:30:34.503

@clcto: this is C, not C++. Try using the C compiler on ideone. – Kyle Kanos – 2014-07-10T10:21:24.087

@KyleKanos ah, ok. When did C remove the need to forward declare functions? – clcto – 2014-07-10T15:50:58.597

@clcto: Forward declaration isn't necessary if you have a multi-pass compiler.

– Kyle Kanos – 2014-07-10T15:56:30.113

3@cicto Forward declaration was never necessary in C, since all arguments and return values are assumed to be int unless specified otherwise. – fluffy – 2014-07-11T07:28:58.380

3

Easytrieve Plus

(http://www.ca.com/us/devcenter/ca-easytrieve.aspx)

FILE PICKLES

JOB INPUT PICKLES
    (any valid code here)

The above code processes the file called PICKLES, a record at a time, until end-of-file is reached.

To actually do something in a loop-construct:

W-COUNT-THE-LOOPS W 3 P 0

JOB INPUT NULL

W-COUNT-THE-LOOPS = W-COUNT-THE-LOOPS + 1
* do what you like here
IF W-COUNT-THE-LOOPS EQ 50 . * or define a field
    STOP
END-IF

Specifying INPUT NULL is referred to as "controlled file processing", where, rather than allowing the language to read records for you, you use GET and check for end-of-file yourself (and the STOP or STOP EXECUTE).

However, there is no rule that says you have to have a file :-)

This program will just loop (as in Big Fat Loop):

JOB INPUT NULL

Similar types of thing may be possible in RPG and its variants (no, not same "game engine").

AWK and others have the automatic reading, but I don't know if it can be done a number of times greater than the number of records on the input file(s).

Bill Woodger

Posted 2014-07-09T12:42:59.023

Reputation: 1 391

3

Python 2

Going for abuse of the rules here. f is implemented without using variables (only arguments), so how can there be "a function that calls itself" within it?

f = (lambda r: lambda f: r(lambda g: f(lambda n: g(g)(n)))) \
    (lambda h: h(h))(lambda R: lambda n: 1 if (n < 2) else (n * R(n - 1)))
print f(5)  # 120
print f(10)  # 3628800

By removing whitespace, the f expression can be reduced to 112 characters.

wberry

Posted 2014-07-09T12:42:59.023

Reputation: 281

Yes, this is a fixed point function like but not exactly the Y combinator. – wberry – 2015-09-11T14:51:52.967

3

HTML + Javascript

Simple loop by calling events. Do not try in the browser, as it won't respond anymore...

<!DOCTYPE html>
<html>
    <body>
        <input id="text1" type="text" onFocus="javascript:change('text1', 'text2')"/>
        <input id="text2" type="text" onFocus="javascript:change('text2', 'text1')"/>
    </body>
    <script>
        change('text1', 'text2');
        function change(current, next) {
            var field = document.getElementById(current);
            field.value = field.value + "1";
            document.getElementById(next).focus();
        }
    </script>
</html>

CommonGuy

Posted 2014-07-09T12:42:59.023

Reputation: 4 684

1Don't know if it doesn't count as indirect recursion seeing that you're operating on events bound to different elements - you call focus on element A which calls focus on element B which calls focus on element A etc. On the other hand it's using two languages, and the approach won't work without one or the other, so there's moving between interfaces somewhere in there, so my first point might not be true. – eithed – 2014-07-10T09:40:56.350

3

T-SQL

Since there already was one example posted using events, I thought why not give a TSQL example using events, ehm, triggers I mean.

Yes this uses recursion (but not in the sense of OP's definition [a function calling itself]), but it is merely a trigger getting triggered by an operation that is done within itself:

CREATE TABLE InfiniteFun (LuckyNumber INT)

GO

CREATE TRIGGER InfiniteFunAction
ON
dbo.InfiniteFun
AFTER INSERT

AS

IF (TRIGGER_NESTLEVEL() < 32) -- maximum nest level seems to be 32 by default
BEGIN
    INSERT InfiniteFun (LuckyNumber)
        SELECT
                LuckyNumber
            FROM inserted
END

GO

You might have to allow for trigger recursion on that particular database:

DECLARE @myDb VARCHAR(MAX) = db_name()
EXECUTE('ALTER DATABASE ' + @myDb + ' SET RECURSIVE_TRIGGERS ON')

Now you can run

INSERT InfiniteFun (LuckyNumber)
    SELECT 42

which honestly does not last forever, but results in a few more inserts than just the one explicitly written.

DrCopyPaste

Posted 2014-07-09T12:42:59.023

Reputation: 131

I didn't realize triggers could be recursive. Even more reason to avoid them in my book :) – Michael B – 2014-07-10T19:09:42.593

3

Java, threads

import java.util.concurrent.atomic.AtomicInteger;

public class Loop {
    public static void main(String[] args) {
        // loops counter
        final AtomicInteger counter = new AtomicInteger(10);
        new Runnable() {
            @Override
            public void run() {
                if (counter.getAndDecrement() > 0) {
                    // payload start
                    System.out.println("Loop " + counter.get());
                    // payload end

                    // repeat while counter is gte zero
                    new Thread(this).start();
                }
            }
        }.run(); // initial start of loops
    }
}

Every thread starts new thread with same payload, until counter hits zero.

Tomáš Dvořák

Posted 2014-07-09T12:42:59.023

Reputation: 621

3

Redcode 94

Edit 2: This is another way to do it. SPL 0 splits to two threads, where the first one continues and the second one spawns at the same instruction, thus creating infinite amounts of threads, while executing the code following it. When a thread hits DAT, it is killed. The famous dwarf:

        org    start
start   spl    0           ; Split infinitely
        add.ab #4   ,   2  ; Add 4 to the B-field of the dat
        mov.i  1    ,   @1 ; Copy the dat to the location pointed by it's B-field
        dat    #0   ,   #0
        end

All this is because of Ilmari Karonen's self terminating program. So, in Redcode looping always requires some kind of jumping. Because of that, I decided to create a program which copies itself completely, and jumps to the start of the new program after that, thus replicating itself infinitely.

Edit: The old version was convoluted.

; Set some constants
length equ 8              ; The program is 8 instructions long
step   equ length         ; When step equals the length, the program copies itself after one empty space
jump   equ (step+start+1) ; This points to the start location of the copy

        org    start
ptr     dat    #1        ,    #0
targ    dat    #1        ,    #0
leaf1   mov.ab #step     ,    targ  ; Reset the target
leaf2   mov.i  >ptr      ,    >targ ; Copy *ptr++ -> *targ++
        slt    #length   ,    ptr   ; Jump back if ptr < length
        jmp    leaf2
        jmp    jump                 ; When done, jump to the start of the new program.
start   ; The loopable code can be placed here
        ; ...all the way until
        jmp leaf1
        end

So, if this code is run, the execution starts from the label start (big surprise). The leaf subprogram does the copying. That subprogram can handle any size of a program, as long as it's the first part of it. I'll show you what the program looks like in the memory (hand compiled for brevity):

Iteration 1
0000    dat    #1        ,    #0
0001    dat    #1        ,    #0
0002    mov.ab #8        ,    -1
0003    mov.i  >-3       ,    >-2
0004    slt    #8        ,    -4
0005    jmp    -2
0006    jmp    10
0007    jmp    -5  (execution starts here)

Iteration 2
0000    dat    #1        ,    #0
0001    dat    #1        ,    #0
0002    mov.ab #8        ,    -1
0003    mov.i  >-3       ,    >-2
0004    slt    #8        ,    -4
0005    jmp    -2
0006    jmp    10
0007    jmp    -5  (execution starts here)
0008    <empty>
0009    dat    #1        ,    #0
0010    dat    #1        ,    #0
0011    mov.ab #8        ,    -1
0012    mov.i  >-3       ,    >-2
0013    slt    #8        ,    -4
0014    jmp    -2
0015    jmp    10
0016    jmp    -5  (execution continues here)

seequ

Posted 2014-07-09T12:42:59.023

Reputation: 1 714

3

C (sort of)

#include <stdio.h>
#include <stdint.h>

void
f(uintptr_t x)
{
        printf("FOO !\n");
        *((uintptr_t *)&x - 1) = (uintptr_t)f;
}

int
main(void)
{
        f(42);
        return 0;
}

Compile it on some x86-based Linux in 32-bit mode, with no optimization:

gcc -m32 -W -Wall -o foo foo.c

Then run it. It prints "FOO !" indefinitely.

How it works

When a function is called, the return address is pushed on the stack immediately over (that is, below, since the stack grows backwards) the function argument. The code replaces that return address to that of the f() function itself, so when it returns it starts again. There is no accumulation on the stack, so no stack overflow, which is why it runs forever. This does not work in 64-bit mode because then the argument is passed in a register, not on the stack, and the address computation is then wrong.

Thomas Pornin

Posted 2014-07-09T12:42:59.023

Reputation: 191

So basically the same as http://codegolf.stackexchange.com/a/33220/11259 ?

– Digital Trauma – 2014-07-10T18:42:16.183

Not exactly... well, it messes with the return address, but it does so with an assumption on where it is instead of using a compiler-specific intrinsic, making it more "underhanded" (and shorter). – Thomas Pornin – 2014-07-10T18:48:32.677

2I guess you're trading compiler specificity for architecture specificity – Digital Trauma – 2014-07-10T18:50:57.440

3

Bash

$ iter_func() { echo "Iteration $1"; }
$ mapfile -n5 -c1 -Citer_func < /dev/urandom
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
$ 

mapfile is usually used to read a file into an array, line-by-line. But it also has the handy feature of optionally calling a callback every c lines. We simply read n lines from /dev/urandom, and call the callback for each line.

Digital Trauma

Posted 2014-07-09T12:42:59.023

Reputation: 64 644

pritty much similar: http://codegolf.stackexchange.com/a/34330/15168

– CousinCocaine – 2014-07-10T18:47:57.743

2@CousinCocaine not really - this one allows arbitrary code to be executed in each loop iteration – Digital Trauma – 2014-07-10T18:49:32.197

1ok, that indeed a little more iteration like than my cat ;) – CousinCocaine – 2014-07-10T19:04:20.327

3

C

This will crash eventually but it could easily be limited.

void exitfn()
{
    static int i;
    printf("%d\n",i++);
    exit(1);
}

void main()
{
    atexit(exitfn);
    exitfn();
}

The idea is that atexit defines a function called when the program exits. If that function happens to contain an exit command ...

As a bonus, it prints out numbers so you can see it is doing something.

Alchymist

Posted 2014-07-09T12:42:59.023

Reputation: 544

Isnt this a a(){b();} b(){a();} type of code? – Martijn – 2014-07-11T12:58:38.040

I think it's a good solution. When it all comes down to it the only real way to solve this problem is by abusing a language feature that loops or recurses, and all of the solutions do it. – Wug – 2014-07-13T08:06:24.397

@Martijn I agree it's indirect recursion but what can you do? I prefer to think of it as a three step process since exitfn calls exit, which causes the process executing the C program to call exitfn. – Alchymist – 2014-07-14T22:30:47.753

3

Come From

Technically it isn't a goto, so:

  COME FROM 1
1 TELL "HI" NEXT

Batch

This is a program that executes itself:

echo HI
%0

frederick

Posted 2014-07-09T12:42:59.023

Reputation: 349

See also A Linguistic Contribution to GOTO-less programming.

– Mark – 2015-09-10T01:53:17.483

3

Forth

A common-enough idiom sometimes known as "factored unrolling". This program prints the numbers between 0 and 99, inclusive. The same technique can be applied to nearly any language, but forth syntax and semantics make the idiom particularly compact and convenient.

: o   dup . 1+            ; \ ones
: t   o o o o o o o o o o ; \ tens
: h   t t t t t t t t t t ; \ hundreds
0 h drop

If you're really tricky you can compute an offset into an unrolled loop like this and produce an equivalent to Duff's Device. The precise implementation of execution tokens in your forth interpreter might make things simpler than shown:

: offset  r> + >r                             ;
: b       dup . 1+                            ;
: a       dup offset b b b b b b b b b b drop ;
1 a cr 3 a cr 8 a cr

Which prints:

1 2 3 4 5 6 7 8 9 
3 4 5 6 7 8 9 
8 9

Another fun trick is rewriting the return stack. This program does exactly the same thing as the first example:

: rewind   dup 99 < if r> dup 1 - >r >r then ;
: main     0 rewind dup . 1+                 ;
main drop

The precise mechanics of this are highly implementation dependent, but the above seems to work on JSForth. The idea is that the call to rewind stores a position inside main on the rstack and then rewind conditionally rewrites the stack so that when main returns it returns back into main just before rewind was originally called.

JohnE

Posted 2014-07-09T12:42:59.023

Reputation: 4 632

there's a 1+ word. were this codegolf, it would save a byte but even so, it's preferred. – cat – 2016-01-04T15:06:34.877

@cat A fair point. JS-Forth does include 1+; I was just being overly cautious. Many small Forth implementations omit helper words like that and I was trying to quickly produce a proof of concept with an unfamiliar interpreter.

– JohnE – 2016-01-04T16:18:50.357

Well, the only Forth implementations I trust are gforth and the paid one released by Forth, Inc or whatever. Since the "main" part of your answer doesn't specify JSForth, it should be fine to use the gforth standard. – cat – 2016-01-04T18:12:55.383

1Any kind of rstack-twiddling trick (especially the duff's device one I added) has a good chance of being implementation-dependent, and JS-Forth is much easier for the casually interested public to play with than gforth since it doesn't require installation. – JohnE – 2016-01-07T18:14:03.683

2

VBA:

Sub rep()
application.displayalert = false
twb = ThisWorkbook.Path & "\" & ThisWorkbook.Name
Workbooks.Open (twb)
End Sub

*It keeps opening the same excel spreadsheet which contains this function when the workbook's opened

Alex

Posted 2014-07-09T12:42:59.023

Reputation: 369

2

Smalltalk

Transcript showCR:'hello'.
thisContext restart

explanation:

thisContext refers to the currently executed method's stack frame (or continuation, for lispers). It understands a number of nice messages, among others one to restart the current method. Normally, this is used by the debugger. to restart a method after achange, but... ...this one runs forever.

blabla999

Posted 2014-07-09T12:42:59.023

Reputation: 1 869

2

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

Hovercouch

Posted 2014-07-09T12:42:59.023

Reputation: 659

Is this C? Can't tell – CailinP – 2014-07-11T00:34:56.220

@CailinP Whoops forgot to mention it was Python – Hovercouch – 2014-07-11T00:36:21.243

Makes sense. I like this! – CailinP – 2014-07-11T00:37:00.337

2

JQUERY

Instead of having the function call itself, it can just trigger an event that causes itself to be called...

$('#go').click( function() {
   alert("Hello!");
   $('#go').trigger('click');
});

John Chrysostom

Posted 2014-07-09T12:42:59.023

Reputation: 121

Isn't that againt the "no recursion"-rule? – german_guy – 2014-07-10T13:20:02.810

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 – 2014-07-10T15:38:09.767

1You could add .trigger('click'); after the click() function to auto-init :) – Martijn – 2014-07-11T08:53:50.973

2

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.

user3188175

Posted 2014-07-09T12:42:59.023

Reputation: 329

2

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.

Paul Butcher

Posted 2014-07-09T12:42:59.023

Reputation: 221

2

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,

Fridolin

Posted 2014-07-09T12:42:59.023

Reputation: 21

2This is indirect recursion, so your answer is invalid – William Barbosa – 2014-07-11T12:20:31.300

1OP: "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 – 2014-07-15T13:53:25.497

2

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

dbrower

Posted 2014-07-09T12:42:59.023

Reputation: 121

2

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

joeytwiddle

Posted 2014-07-09T12:42:59.023

Reputation: 601

2

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.

kolrabi

Posted 2014-07-09T12:42:59.023

Reputation: 121

2

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

enter image description here

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!

Azeirah

Posted 2014-07-09T12:42:59.023

Reputation: 121

2

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

Alchymist

Posted 2014-07-09T12:42:59.023

Reputation: 544

2

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.

Sergey Telshevsky

Posted 2014-07-09T12:42:59.023

Reputation: 127

Funny thing is, this is just a better worded version of the Python one. A minor difference which makes me like this answer. – seequ – 2014-07-15T13:36:51.877

@TheRare I must've missed the python one in all these answers :) – Sergey Telshevsky – 2014-07-15T13:39:35.237

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 – 2014-07-15T13:41:03.813

@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 – 2014-07-15T13:43:09.050

2

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

tobyink

Posted 2014-07-09T12:42:59.023

Reputation: 1 233

2

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

bacchusbeale

Posted 2014-07-09T12:42:59.023

Reputation: 1 235

1

Perl

$b = ($i = <>) - ~-$i;
{
    ($b, $a) = ($a + $b, $b);
    redo if --$i
}
print "$a\n";

This takes an input from STDIN and prints the n-th Fibonacci number.

($i = <>) initializes $i with the input. Then $b is set to 1 by a bit of bit manipulation and subtraction. The "magic" here is done by the redo operator. It makes it possible to reevaluate the same block, without the need of loop. The calculation of $a and $b is redone until the subtraction of one by $i evaluates to False i.e. 0. I think that the print statement in the end is self-explanatory.

Here's one more solution using map instead of redo:

print ~~ (
    map {
        ($b, $a) = ($a + $b, $b)
    } ++$b .. <>
)[-1] . $/;

This generates an array of up to the requested number of the Fibonacci sequence and prints the last entry. ++$b initializes $b to 1. Then the end of the rage, generated by .., is read by <>. map iterates it and the calculation is returned as an array. Then [-1] uses the last element to print.

core1024

Posted 2014-07-09T12:42:59.023

Reputation: 1 811

The question explicitly forbade "A programming language statement which allows code to be repeatedly executed" like redo. – msh210 – 2016-01-04T19:31:38.707

1

C#

Since we can't loop... why don't we use events instead?

static void Main(string[] args)
{
    var timer = new Timer(1000);
    timer.Elapsed += (o,e) => Console.WriteLine("Cheese!");
    timer.Start();
    Console.ReadLine();
}

NPSF3000

Posted 2014-07-09T12:42:59.023

Reputation: 374

1

This is pretty cheap I guess.

I think semanatically, you can argue that the constructor isn't directly calling itself.

Python

class MyClass:
    i = 0
    subClass = None
    def __init__(self, i):
        self.i = i
        if i != 5:
            self.subClass = MyClass(i+1)
        print self.i

c = MyClass(1)

dwjohnston

Posted 2014-07-09T12:42:59.023

Reputation: 111

Also __getattr__ or __eq__. :P – cjfaure – 2014-07-10T12:15:31.760

1

Visual Basic 6.0

Public Function TimerOn(Interval As Integer)
    If Interval > 0 Then
        ' Start the timer.
        Timer1.Interval = Interval   
    Else
        ' Stop the timer.
        Timer1.Interval = 0 
    End If
End Function

Mohit Shrivastava

Posted 2014-07-09T12:42:59.023

Reputation: 111

1

Python

Pretty similar to @dwjohnston's answer.

class z:v=c
g=z()
def f():z.v-=1;y();return z.v!=0
class x:__eq__=lambda s,x:s==x if f()else 1
x()==0

Assumes that y is the function you want to call c times (set c to a negative number for infinite, though it hits the recursion depth limit pretty quickly)

cjfaure

Posted 2014-07-09T12:42:59.023

Reputation: 4 213

1

Emacs Lisp

Jordon Biondo already mentioned this, but here is a very minimalistic version of the macro based loop. It uses the backquote and comma syntax to save some evals:

(defmacro macroloop (s n)
  (if (> (eval n) 0)
      (progn
        (macroexpand `(macroloop ,s ,(- n 1)) )
        (print s)
        )
    )
  )

(macroloop "hello world" 10)

Arne

Posted 2014-07-09T12:42:59.023

Reputation: 121

Better not use this for too long loops. – seequ – 2014-07-10T16:30:18.620

Yup, same goes for (non-tail) recursion. :) – Arne – 2014-07-10T21:03:51.927

1

SQL (oracle 10g or above)

select level from dual connect by 1=1;

This will generate rows from 1 to infinite.

ntalbs

Posted 2014-07-09T12:42:59.023

Reputation: 131

1

php

Very simple method, this happens every once in a while when not paying attention:

header('Location: thisPage.php');

Martijn

Posted 2014-07-09T12:42:59.023

Reputation: 713

shouldn't it be header('Location: '.$_SERVER['PHP_SELF']);? – eithed – 2014-07-11T21:41:59.560

Doesn't really matter. Choose this because I thought this might look simpler – Martijn – 2014-07-12T11:28:37.570

1

JavaScript

Small loop when listening on DOM tree modification :

var int=0;
document.addEventListener('DOMNodeInserted', function(){
    int++;
    console.log('Loop ' + int);
    if(int < 5) document.body.appendChild(document.createElement('div'));
});
document.body.appendChild(document.createElement('div'));

It just add an element and retrigger the event.

Karl-André Gagnon

Posted 2014-07-09T12:42:59.023

Reputation: 141

1

Public Event e()

Public Function a() Handles Me.e

   RaiseEvent e()

End Function

a()

mmm

Posted 2014-07-09T12:42:59.023

Reputation: 11

Is this Visual Basic? – jimmy23013 – 2014-07-11T16:01:28.563

1

C

This is a fork bomb. It is not a "function that calls itself" but instead is a "program that calls itself".

int main(int argc, char **argv)
{
    fork();
    printf("Hello world\n");
    return system(argv[0]);
}

Ken A

Posted 2014-07-09T12:42:59.023

Reputation: 585

1

Java Swing

import java.awt.event.*;
import javax.swing.JButton;

public class Looper {
    public static void main(String[] args) {
        final JButton button = new JButton();
        new JButton().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                button.doClick();
            }
        });   
        button.doClick();
    }
}

Tom

Posted 2014-07-09T12:42:59.023

Reputation: 111

1

Haskell

main=foldr1 (>>) $ repeat $ putStrLn "Yolo

Repeatedly displays "Yolo".

Note: Folds and repeat are not structures, they are functions

Note: I did not specify which implementation of prelude I am using. Therefore, the above functions do not necessarily use recursion. The haskell standard specifically says that any implementation of foldr1 and repeat with the same semantics as the above are valid, even without recursion.

PyRulez

Posted 2014-07-09T12:42:59.023

Reputation: 6 547

1

C# threaded solution

You'll need to turn off catching for the DangerousThreadingAPI exception for this to work correctly without stopping. make sure to include the System.Threading library with a using statement at the start of the program

    int mycounter = 0;
        Thread themainthread = Thread.CurrentThread;
        System.Action<object> thethreadworkoriginal= new System.Action<object>((actionobject) =>
        {

            System.Action<object> theotheraction = (System.Action<object>)actionobject;
            Console.WriteLine(mycounter);
            mycounter++;
            if (mycounter == 10)
            {
                themainthread.Resume();
                return;

            }
            ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(theotheraction), theotheraction);

        });

        System.Action<object> thethreadworknew = new System.Action<object>((actionobject) =>
     {

         System.Action<object> theotheraction = (System.Action<object>)actionobject;


         ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(thethreadworkoriginal),thethreadworkoriginal);
     });


        Thread thestartingthread = new Thread(new ParameterizedThreadStart(thethreadworknew));   
        thestartingthread.Start(thethreadworkoriginal);
        //let the "loop" finish
        themainthread.Suspend();
        Console.WriteLine(mycounter);

user29252

Posted 2014-07-09T12:42:59.023

Reputation: 11

the function doesn't call itself but it makes a new thread that runs the calling action – user29252 – 2014-07-11T20:26:16.817

the second action takes the first as a parameter, and runs it over and over until the counter hits the target,all while the main thread of the program is suspended and waiting for the target to be hit so it can be awoken. Yes it's an intentional race condition but it's safe. – user29252 – 2014-07-11T20:30:20.960

to clarify, the first action is running a copy of itself over and over, by creating new threads in the thread pool, and this is why I had to create two separate actions, as an action cannot possibly know the definition of itself inside of its own declaration unless it has been declared already elsewhere. – user29252 – 2014-07-11T20:59:15.573

1

JavaScript with HTML

If you put this tag into a page, your hit-counter will soar! (In the short term anyway.)

<script>
    var oldLocation = window.location;

    window.location = 'middle.nowhere';

    window.location = oldLocation;

    alert('You shouldn\'t have tried this.');
</script>

Yet another browser breaker. Shockingly easy. It's safe to run the code once, but don't put the tag on a page and try to load it unless you're done browsing for a while.

Edit: I missed it in my prior searching, but Pichan beat me to posting this concept. My answer explains how to use this code and includes handling for an extra edge-case, so I'm leaving it up until I'm led to believe that this is bad etiquette.

Keen

Posted 2014-07-09T12:42:59.023

Reputation: 261

1

Scala

def while_(cond: => Boolean)(f: => Unit): Unit = Stream.continually(f).find(_ => !cond)

Example usage:

var i = 1
while_(i <= 100) {
  println(i)
  i = i + 1
}

Prints out 1 through 100, in order.

Joe K

Posted 2014-07-09T12:42:59.023

Reputation: 1 065

1

Rebol

loopy: function [times block] [
    loop: copy []
    append/dup loop block times
    do loop
]

Usage example in Rebol console:

>> loopy 3 [print "hello world!"]
hello world!
hello world!
hello world!

The loopy function takes a block of code and simply duplicates itself the necessary number of times into a series (array) called loop (see append/dup loop block times). Then it just evals that loop series with do loop.

So if you could see the loop series within the above example it would look like this:

[print "hello world!" print "hello world!" print "hello world!"]

So code being data then this is what happens:

>> do [print "hello world!" print "hello world!" print "hello world!"]
hello world!
hello world!
hello world!

draegtun

Posted 2014-07-09T12:42:59.023

Reputation: 1 592

1

JavaScript

code = 'alert(\' Lorem Ipsum \');';
num = 5;
eval(new Array( num + 1 ).join( code ));

num is the number of times to repeat the code in the string code. This repeats the String code the number of times in num and executes it with eval.

Cilan

Posted 2014-07-09T12:42:59.023

Reputation: 724

What language is this? – raptortech97 – 2014-07-15T13:59:20.860

@raptortech97 JavaScript – Cilan – 2014-07-15T15:56:41.320

1

JavaScript

Warning: This may kill your browser.

(function(){
    arguments.callee.call(this);
})();

What happens here is, we've used the SEAF or Self Executing Anonymous Function to execute a function that will simply call it's callee again (so technically no recursion as the method is not calling itself :) ). The callee is again the SEAF and as such executing this will result in:

Uncaught RangeError: Maximum call stack size exceeded

thomaux

Posted 2014-07-09T12:42:59.023

Reputation: 219

1

Javascript

<script>
    var button = document.createElement('button');
    button.addEventListener('click', document.createElement);
    window.onerror = setTimeout.bind(window, button.click);
    button.click();
</script>

Explanation: document.createElement() expects a parameter, so clicking the button causes an error to be thrown. The window catches the error and dispatches another click to the button. I don't think this meets the definition of recursion provided since the browser's event loop is invoking the error handler.

aebabis

Posted 2014-07-09T12:42:59.023

Reputation: 433

1

JavaScript

eval(Array(9).join("alert('loopy');"));

Ben

Posted 2014-07-09T12:42:59.023

Reputation: 131

First glance I read "evil array" – Mark Jeronimus – 2015-09-12T16:23:36.900

1

ZX Spectrum Basic

10 PRINT "Hello"
20 POKE 23618,10:POKE 23619,0:POKE 23620,1

This uses the system variables to execute a goto.
The first 2 POKEs specify the line number
The last POKE specifies which statement on that line, and causes the goto to execute

SeanC

Posted 2014-07-09T12:42:59.023

Reputation: 1 117

1

J

Some bit twiddling in J

-^:_] 1

Broken down:

  • - : change sign of input
  • ^: power conjunction. With right argument _ (infinity): return a verb which does do the left argument till convergence (in this case: forever)
  • 1 : argument to the derived verb

This effectively keeps changing the sign of one till you break the process.

jpjacobs

Posted 2014-07-09T12:42:59.023

Reputation: 3 440

1

Tcl

# I'd like to call "if" "when" instead.
rename if when
when 0 do stuff

if expresion then else - will execute stuff
stuff is not defined, so unknown is called, which uses if, which does not exist - calling unknown

Johannes Kuhn

Posted 2014-07-09T12:42:59.023

Reputation: 7 122

1

Unlambda

``cc`cc

Loops infinitely. ("Verify" it here.) Abuse of the language's call with current continuation primitive c.

wberry

Posted 2014-07-09T12:42:59.023

Reputation: 281

1

><>

This code uses the fact the ><> (fish) wraps around to execute the trampoline instruction repeatedly, jumping over itself like a lonely leap-frog.

!

mbomb007

Posted 2014-07-09T12:42:59.023

Reputation: 21 944

1

Java

new Timer().schedule(new TimerTask() {
    public void run() {
        System.out.println("Loop without Looping");
    }
}, 0, 1);

HyperNeutrino

Posted 2014-07-09T12:42:59.023

Reputation: 26 575

1

68k Assembly

This will only work if the code is stored in writable memory. It's low-level enough that it might work differently on different platforms, but it's verified to work on the EASy68k simulator.

    ORG $1000
START:
    ; Set value that counter will count down from
    MOVE #5,D1

    ; call counter (and as a side-effect, store the current value
    ; of the program counter + 4 on the stack so it will still work even
    ; if the code is loaded somewhere other than 0x1000)
    JSR counter

    ; Exit program
    MOVE.B #9,D0
    TRAP #15 

counter:
    ; Modify the value of the ADDQ instruction in-memory so it does a
    ; conditional branch instead of undoing the subtraction
    MOVE.L (SP),A0
    ADD.W #$1af5,22(A0)

    ; print value in D1 as integer
    MOVE.B #3,D0
    TRAP #15 

    ; D1 = D1 - 1 + 1 
    SUBQ.B #1,D1
    ADDQ.B #1,D1

    ; return
    RTS

    END START

Ray

Posted 2014-07-09T12:42:59.023

Reputation: 1 488

1

JAVA

I'm so surprise nobody used non-static initializer block yet.

public class Pear {

    {
        System.out.println("Hello non-static initializer");
        new Pear();
    }


    public static void main(String[] args) throws IOException {
    new Pear();
    }
}

This will print out "Hello non-static initializer" till it will throw StackOverflow error

user902383

Posted 2014-07-09T12:42:59.023

Reputation: 1 360

0

Python 2.7

I presume building a list isn't technically looping. Because if so, this works

def forLoop(x):
  print "hello"

map(forLoop, range(0,5))

gives:

0 hello
1 hello
2 hello
3 hello
4 hello

user8777

Posted 2014-07-09T12:42:59.023

Reputation:

I got a different output ("hello" 5 times followed by a list of None's), but the "loop" still works. – ApproachingDarknessFish – 2014-07-11T00:26:08.420

did you print the result from the map? because if you don't assign the map function to anything it is run but not stored. – None – 2014-07-11T00:28:07.497

This actually prints "hello" 5 times and returns a list of five Nones. I would call it fine, but your result is a little misleading. – seequ – 2014-07-13T22:44:30.083

0

BASH

cat /dev/random

It repeatedly prints random to the screen without using any repetition. Simple as that. Theoretically you can use any input device.

CousinCocaine

Posted 2014-07-09T12:42:59.023

Reputation: 1 572

It complies with the rules: 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). – CousinCocaine – 2014-07-10T17:40:07.367

2Not very general, is it? Also I would argue that is just one non-repeated command. – seequ – 2014-07-10T17:40:10.247

@TheRare, what do you mean? – CousinCocaine – 2014-07-10T17:41:33.533

1You're just calling cat with an infinite source. I wouldn't say you're repeatedly calling cat. – seequ – 2014-07-10T17:42:14.837

It does what is asked: "repeatedly executes code without using any repetition structures such as while, for, do while, foreach or goto". I agree, it feels like cheating, but it is not. – CousinCocaine – 2014-07-10T18:44:45.937

0

PHP

This one's kind of borderline recursive. The code calls itself through eval().

$max = 10;
$i = 0;

$e = <<<'EOS'
    echo "Spudro sp&auml;rde $i<br>";

    $i++;
    if ($i < $max)
        eval($e);
EOS;

eval($e);

Pichan

Posted 2014-07-09T12:42:59.023

Reputation: 241

0

Call this codgolf0.py, run with python codegolf0.py 0

from subprocess import call 
import sys
import os

i = int(sys.argv[1])
print i
call( "copy /y codegolf"+str(i)+  ".py codegolf"+str(i+1)+".py >nul ", shell=True)

if i<10:
    call("python codegolf"+str(i+1)+".py "+ str(i+1), shell=True)

Admittedly, copying the .py isn't necessary, could just use repeated system calls to the python. The way I got to this was by getting the python to manually write the new python script, before I realised I was chasing my tail.

dwjohnston

Posted 2014-07-09T12:42:59.023

Reputation: 111

0

Java

Looping without loops? Why not just use a Timer?

import java.util.Timer;
import java.util.TimerTask;

public class TimerLoop {
    private static class LoopTask extends TimerTask {
        private int count = 99;
        private final Timer timer;

        public LoopTask(Timer timer) {
            this.timer = timer;
        }

        @Override
        public void run() {
            --count;
            if (count < 0) {
                timer.cancel();
                return;
            }
            System.out.println(count + " bottle(s) of beer on the wall...");
        }
    }

    public static void main(String[] args) {
        Timer t = new Timer();
        t.schedule(new LoopTask(t), 0, 100);
    }
}

Andreas Baus

Posted 2014-07-09T12:42:59.023

Reputation: 1

There are already two answers which do exactly this. That's one more than necessary. – Peter Taylor – 2014-07-11T10:18:48.037

0

R

I am not sure if this is allowed.

lapply(letters, print)
  1. The first argument is a vector (list) - letters in this case.
  2. The second argument is a function to be applied on each element of the first argument.
  3. The output is a list of values - the result of the function.

djhurio

Posted 2014-07-09T12:42:59.023

Reputation: 1 113

1Can you explain what this code-snippet does? – CommonGuy – 2014-07-11T11:25:18.327

1If I could take a stab at this, letters is a built-in vector a-z, print is the built-in print function, and lapply applies the function to every member of a vector/array/matrix/dataframe and then puts them together and returns the result. Interestingly, print returns the printed object as a character vector, so at the interactive prompt this program prints out all the letters a-z and then prints them out again because they are the output of lapply. – raptortech97 – 2014-07-15T13:57:33.797

0

Bash

coproc a { bash; }
echo "x='echo \$x;echo y >&2'" >&${a[1]}
echo 'echo $x' >&${a[1]}
cat <&${a[0]} >&${a[1]}

It has the same output as yes, but to stderr.

jimmy23013

Posted 2014-07-09T12:42:59.023

Reputation: 34 042

0

<html>
<script>
function method()
{
    //do something
    location.reload();
}
</script>
<body onload="method()">
</body>
</html>

It keeps reloading the web page.

TAAPSogeking

Posted 2014-07-09T12:42:59.023

Reputation: 101

0

Golfscript, (24 + message)

".{('All work and no play makes Jack a dull boy\n'print W~}{;}if":W~

Takes an integer 'n' off the stack and prints the given string n times.

Each iteration checks if there are more iterations to go, and if so, it prints the message and pushes a copy of the execution code onto the stack.

The code for each iteration is stored in the variable 'W'.

This method can be used as a work-around for the issue with nested 'while' loops in the online golfscript interpreter.

Kyle McCormick

Posted 2014-07-09T12:42:59.023

Reputation: 3 651

0

REXX:

x = 1
say "Now" x; x=x+1; if x<5 then interpret SOURCELINE(2)
exit

Output:

Now 1
Now 2
Now 3
Now 4

Explanation:

  • SOURCELINE(n) retrieves source line n as a string, usually for displaying lines that return exceptions.
  • The INTERPRET instruction takes a string parameter and passes it to the REXX interpreter which executes the string as if it were part of the program wrapped in a simple DO...END block (which therefore keeps procedure variables in scope).

The IF test keeps the "loop" down to 4 executions.

user2338816

Posted 2014-07-09T12:42:59.023

Reputation: 101

0

Common Lisp

I wrote a macro (not a function, so it isn't using recursion as defined).

(defmacro myloop (num &body body)
  (if (= num 1)
    `(progn ,@body)
    `(progn ,@body (myloop ,(- num 1) ,@body))))

To execute (myfunc arg) 4 times, just

(myloop 4 (myfunc arg))

This will generate code that looks like:

(progn
  (myfunc arg)
  (progn
    (myfunc arg)
    (progn
      (myfunc arg)
      (progn
        (myfunc arg)))))

protist

Posted 2014-07-09T12:42:59.023

Reputation: 570

0

D

Using templates and string mixins.

import std.stdio;

void main() {
    mixin(MeinLoop!(`"You said a *function* couldn't call itself!"`, 100));
}

template MeinLoop(string message, int n) if(n > 0) {
    enum MeinLoop = "writeln(" ~ message ~ ");" ~ MeinLoop!(message, n - 1);
}

template MeinLoop(string message, int n) if(n <= 0) {
    enum MeinLoop = `writeln("Done!");`;
}

Cleaner version:

import std.stdio;

void main() {
    mixin(MeinLoop!(`"You said a *function* couldn't call itself!"`, 100));
}

template MeinLoop(string message, int n) {
    static if(n <= 0) {
        enum MeinLoop = `writeln("Done!");`;    
    } else {
        enum MeinLoop = "writeln(" ~ message ~ ");" ~ MeinLoop!(message, n - 1);
    }
}

This prints message n times before printing "Done!", and as templates and mixins are not functions, this seems to abide by the rules.

How it works:

At compile time, mixin injects whatever string it is passed into the program as code. In our case, we handed it a template with evaluates to a string containing statement which prints message to stdout, and the template then recurses until n copies of the string are injected into the file. Since we were instructed to not use recursive functions, this is valid.

Sheev

Posted 2014-07-09T12:42:59.023

Reputation: 1

0

Python

#!/usr/bin/env python
import os
import sys
class FakeLoop(object):
    def __init__(self):
        self.execl = os.execl
        self.path = sys.argv[0]
    def __del__(self):
        self.execl(self.path, '')
fakeloop = FakeLoop()
print 'loop'

It's like tail-recursion for processes!

Fraxtil

Posted 2014-07-09T12:42:59.023

Reputation: 2 495

0

MOS6502version

$FFD2 is the CHROUT Kernal call on Commodore 8bit computers and prints the char in .a to the current output device. Change the $FFD2 to the correct address of "Print char in .a" for use on other 6502 computers.

Called from BASIC using SYS5000, this prints the alphabet ABC...XYZ on a single line, then returns to the BASIC prompt.

*=$1386
.BYTE 0,0 ; char & count storage
ENTER=* ; use "SYS5000" from BASIC prompt to execute
    LDA #"A"-1    ; initial character to print is A
    STA  ENTER-2
    LDA #26       ; print 26 characters
    STA  ENTER-1
    LDA #>ENTER-1 ; high byte of addr-1
    PHA
    LDA #<ENTER-1 ; low byte of addr-1
    PHA
    DEC  ENTER-1  ; Countdown finished when -1
    BPL  PRT
    PLA           ; clean the stack
    PLA
    RTS           ; and return to caller
PRT=*
    INC  ENTER-2  ; update char to print
    LDA  ENTER-2  ; print the char and continue
    JMP  $FFD2    ; Actually a JSR, the return addr was put on stack earlier

Technically, this and the earlier x86 code use GoTo as the RTS/RET will goto the address on the stack when executed.

It works nicely to implement a case statement in 6502 :)

user29299

Posted 2014-07-09T12:42:59.023

Reputation: 1

0

Well since people seem to like redcode:

SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
SPL 1
MOV.I 1, {-1

Erases all of memory under standard configuration then dies.

Joshua

Posted 2014-07-09T12:42:59.023

Reputation: 3 043

0

JavaScript (in an old-ish browser)

var el = document.createElement('input');
el.onfocus = function() {
  alert("ha");
};
document.body.appendChild(el);
el.focus();

In older browsers, the alert will cause the input to be temporarily unfocused; when you dismiss the alert, the input will be re-focused and trigger the event handler again. And so on until you get annoyed and kill the process.

Unfortunately, though I distinctly remember seeing this in the past, I wasn't able to get this to happen in any modern browser - looks like it was considered a bug and fixed some time ago. I accept any and all downvotes for the datedness of this technique.

DallonF

Posted 2014-07-09T12:42:59.023

Reputation: 131

0

JAVA using reflection

 public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Golf golf = new Golf();
        golf.notALoop();
    }

    static class Golf{
        public void notALoop() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
            System.out.println("Its not directly calling it self");
            Method method = this.getClass().getMethod("notALoop");
            method.invoke(this);
        }
        }

NimChimpsky

Posted 2014-07-09T12:42:59.023

Reputation: 101

If you are executing the current method then it's recursion, regardless of how you execute it. – Ross Drew – 2014-07-17T07:45:33.067

0

JAVA using a new thread

public class HelloRunnable implements Runnable {
    public void run() {
        System.out.println("to be honest I find this question, not particularly interesting");
        (new Thread(new HelloRunnable())).start();
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }
}

NimChimpsky

Posted 2014-07-09T12:42:59.023

Reputation: 101

0

Haskell

let x = 0:x in x

In GHCI, it prints [0,0,0,.... It uses recursion, but no function calls itself.

Theodore Norvell

Posted 2014-07-09T12:42:59.023

Reputation: 101

0

Bash

Replicator.sh

#!/bin/bash
cat $0 > $1
# do stuff
sh $1 $0

Then call

[user@host ~]$ sh Replicator.sh Replicant.sh

But will it pass the Voight-Kampff test?

KidElephant

Posted 2014-07-09T12:42:59.023

Reputation: 31

0

C# Linq

Prints all numbers 0 - 10 inclusive

Enumerable.Range(0,11).ToList().ForEach(Console.WriteLine);

Nicholas King

Posted 2014-07-09T12:42:59.023

Reputation: 101

too finite I'd suggest. – Jodrell – 2014-07-17T09:29:27.117

Wouldn't ForEach be considered a looping statement? After all, it exists explicitly for the purpose of repeatedly executing code. – celtschk – 2014-07-19T07:20:20.553

its not a loop, its a method called ForEach() that is built into the language. :) – Nicholas King – 2014-07-21T07:54:29.933

0

PowerShell

date
sleep 1
$this = $MyInvocation.MyCommand.Definition
&"$this"

This will print the current date, wait 1 second and then the program will call itself endlessly...

DarkAjax

Posted 2014-07-09T12:42:59.023

Reputation: 669

0

SAS

data _null_;
  set input_ds;
  call execute(" /*Logic goes here*/ ");
run;

There's no explicit do-loop or recursion, but the result is that your logic is executed once for each row in the input dataset.

Not the most creative submission, as the data step is the most fundamental feature of SAS, but I think this is technically correct as the question is currently written - none of the statements used on its own allows repeated execution of code.

EDIT: updated to use call execute to allow for execution of more or less arbitrary logic, rather than just data step logic.

user3490

Posted 2014-07-09T12:42:59.023

Reputation: 809

What is SAS? I bet it doesn't stand for Scandinavian Airlines as Google tries to assure me. – seequ – 2014-07-17T16:27:20.477

http://en.wikipedia.org/wiki/SAS_(software) – user3490 – 2014-07-18T13:22:42.387

0

PHP

My first attempt was almost identical to @Pichan's code:

<?php 
if(!isset($counter)){$counter=1;}
echo $counter;
$counter++;
if($counter > 10){die('That&#39s enough!');}
include(__FILE__);
?>

Then I came up with this, but it might be too close to recursion to count. You dedide:

<?php
$b=null;
$a=function($count){
  if($count > 100){return;}
  global $a; //ugly, I know!
  global $b;
  if($a){
    $b=$a; $a=null;
    echo $count.' ';
    $b(++$count);
  }else{
    $a=$b;
    $b=null;
    echo $count.' ';
    $a(++$count);
  }
};

$a(0);
?>

TecBrat

Posted 2014-07-09T12:42:59.023

Reputation: 222

Whether it REALLY is recursion depends on what actually happens under the hood with $b=$a. And I'm not sure what that is. – TecBrat – 2014-07-15T15:42:04.157

Well, I added a static variable to $a and it persisted, so I guess I'm sunk! I'll leave it up here anyway. (See this: http://sandbox.onlinephpfunctions.com/code/08f47b9116c7f686a10024a3c4f540447932159d)

– TecBrat – 2014-07-15T15:47:03.690

0

PHP

<?php

class a{
    function __destruct(){
        echo new Exception, "\n";
        global $x;
        $x = new a;
    }
}

$x=new a;

It is not a recursion. The destructor only calls the constructor of class a. The destructor itself is called after the destruction of the previous object. The stack always has the same size on each call of the destructor.

A more useful example:

<?php

class a{
    var $i;
    function __construct($i){
        echo "$i\n";
        $this->i = $i;
    }
    function __destruct(){
        global $x;
        if($this->i < 100)
            $x = new a($this->i + 1);
    }
}

$x=new a(1);

Count from 1 to 100.

jimmy23013

Posted 2014-07-09T12:42:59.023

Reputation: 34 042

0

C#

() => Console.Write(DateTime.Now) is just an example that can be eternally repeated. Any other Action can be substituted.

loops eternally.

using System;
using System.Collections;
using System.Linq;

class Program
{
    static void Main()
    {
        new S(() => Console.Write(DateTime.Now)).OfType<Action>().All(
            a =>
                {
                    a.Invoke();
                    return true;
                });
    }
}

class S : IEnumerable
{
    private Action a;

    public S(Action b)
    {
        a = b;
    }

    public IEnumerator GetEnumerator()
    {
        return new L(a);
    }
}

class L : IEnumerator
{
    public L(Action a)
    {
        Current = a;
    }

    public object Current { get; set; }

    public bool MoveNext()
    {
        return true;
    }

    public void Reset()
    {
    }
}

Jodrell

Posted 2014-07-09T12:42:59.023

Reputation: 131

1Recursion is still recursion, even if it's indirect. – seequ – 2014-07-17T13:39:05.097

@TheRare So, There will always be some recursion or the operation cannot repeat. – Jodrell – 2014-07-17T13:51:42.760

I know, I know. I just personally find this a bit too obvious. Not voting in either direction. – seequ – 2014-07-17T14:14:53.217

0

Java

import java.util.Arrays;

public class Main
{
    public static void main( String args[] ) 
    {
        StringBuilder sb = new StringBuilder(1024*1024*4);
        sb.append("x");
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        sb.append(sb.toString());
        String s = sb.toString();
        char[] chars = s.toCharArray();
        String x = Arrays.toString( chars).replace(",", "\n");
        x = x.substring( 1, x.length()-1);
        System.out.println(x);
    }
}

Prints 4194304 lines of 'x'.

barteks2x

Posted 2014-07-09T12:42:59.023

Reputation: 281

It also prints a [ before the first x, and a ] after the last one. – Paŭlo Ebermann – 2014-07-20T09:48:51.990

Edited the code to remove it. – barteks2x – 2014-07-20T11:53:40.050

0

C++

OK, so the task is to do something repeatedly, without using a loop. However, the task does not say how often this has to be done, just that it has to be done repeatedly. So I figure the following program follows all rules, by repeatedly outputting "Hello world":

#include <iostream>

int main()
{
  std::cout << "Hello world\n";
  std::cout << "Hello world\n";
  std::cout << "Hello world\n";
}

Indeed, we can go even shorter: Since the tasks allows to freely choose what the repeated action is, I can just choose the action to be do nothing! Therefore the following program should also qualify, doing nothing a billion times in a row (of course, doing nothing takes no time, so the program terminates immediately):

int main()
{
}

But then, I can also do an infinite hello world "loop", by writing a custom stream buffer:

#include <iostream>
#include <streambuf>
#include <cstring>

class helloworldbuf:
  public std::streambuf
{
public:
  helloworldbuf();
private:
  int_type underflow();

  static char greeting[];
  static char* const end;
};

char helloworldbuf::greeting[] = "Hello world\n";

char* const helloworldbuf::end =
  helloworldbuf::greeting+std::strlen(helloworldbuf::greeting);

helloworldbuf::helloworldbuf()
{
  setg(end, end, end);
}

std::streambuf::int_type helloworldbuf::underflow()
{
    if (gptr() < egptr())
        return traits_type::to_int_type(*gptr());

    setg(greeting, greeting, end);

    return traits_type::to_int_type(*gptr());
}

int main()
{
  helloworldbuf hellobuf;
  std::cout << &hellobuf;
}

celtschk

Posted 2014-07-09T12:42:59.023

Reputation: 4 650

0

Fun With Ruby Exceptions

Essentially, what we do is recursively throw errors until we have what we want, because real loops are for the weak.

The setup code:

class Exception
    alias real_init initialize
    def initialize(*args)
        real_init *args
        if args[0].is_a?(String) && args[0][0] == "\x04"
            hash = Marshal.load(args[0])
            success = send(hash[:condition], hash[:start_position])

            unless success
                hash[:start_position] = send(hash[:next_iteration], hash[:start_position])
                raise Marshal.dump(hash)
            end
            raise hash[:start_position].to_s
        end
    end
end

Example 1:

def condition(x)
    x > 10
end
def next_iteration(y)
    y += 1
end

h = {condition: "condition", next_iteration: "next_iteration", start_position: 3}

begin
    raise Marshal.dump(h)
rescue Exception => e
    puts e
end

Example 2 with strings:

def condition(x)
    x == "lol"
end
def next_iteration(y)
    y.next
end

h = {condition: "condition", next_iteration: "next_iteration", start_position: "lob"}

begin
    raise Marshal.dump(h)
rescue Exception => e
    puts e
end

Make sure you don't get any errors in the next_iteration or condition methods, or you will be getting strange results.

Automatico

Posted 2014-07-09T12:42:59.023

Reputation: 171

0

JavaScript

function foreach(arr, fn, a, i) {
  if (!Array.isArray(a)) {
    a=fn.toString().match(/\(.*?\)/)[0].match(/[^()\s,]+/g);
  }
  if (i >= arr.length) return;
  foreachDo(arr,fn,a,i|0);
}

function foreachDo(arr, fn, a, i) {

  var params = arr.slice(i,i+a.length);
  fn.apply(fn,arr.slice(i,i+a.length));
  i+=a.length;
  foreach(arr, fn, a, i);
}

var people = ["John", "Doe", "Denver", "Jane", "Doe", "Seattle", "Bob", "Doe", "Summerset"];

foreach(people, function(first, last, city) {

  console.log(first + ' ' + last + ', ' + city);

});


John Doe, Denver
Jane Doe, Seattle
Bob Doe, Summerset

wolfhammer

Posted 2014-07-09T12:42:59.023

Reputation: 1 219

0

///

/// is a minimalistic programming language. It has only two commands: "output character literal", and "replace the first occurrence of first string literal with second string literal in the remainder of the program, repeating until the first string literal does not appear in the program".

In both commands, a backslash denotes that the next character is taken literally. The replacement command is /first literal/second literal/, and the output command is any character besides /. So, for example, the program /lo\\c\k/\ake/che\ese\\clo\ck first replaces every occurrence of lo\ck with ake (the \s before the k and the a have no effect), resulting in che\ese\\cake. Then the program executes the printing commands c, h, e, \e, s, e, \\, c, a, k, and e, thereby printing cheese\cake.

Needless to say, writing useful programs in /// is very difficult. The only way for a program to loop (besides using an infinite substitution like in /a/aa/a) is for a part of the program to use substitutions to create a copy of itself later in the program. I've never figured out how to do this, but Ørjan Johansen has written a program which does this:

/|/<-\\\\>\\\\\\//QT/|/R|N|/Q|T|/|/<-|\|\>|/<-|\|\|\|\>|\|\|\|\|/|/<|\->|/|/C|T|/C|\T|/C|T|/|/*|\
|/I|\N|/|/I|\N|/**|\
|/|/Q|\T|/Q|T|/R|N//RN/QT//<-\\>/<-\\\\>\\\\//<\->///CT/*
//Q\T/QT/RN

How does this work? I'm not completely sure, but it's something like this.

The first replacement replaces | (which is just syntactic sugar) with <-\\>\\\. The second replacement replaces the string QT with a quoted version of the second half of the program. In the second replacement command itself, most characters are preceded by <-\\>\\\. The result is that in the string produced by the second replacement, most characters are preceded by <-\>\.

The third replacement looks like it replaces RN with QT. But QT has been replaced with a quoted version of the program, where most characters are preceded by <-\>\. So this replacement actually replaces RN with yet another quoted version of the second half of the program, in which most characters are preceded by <->.

In the fourth replacement, each occurrence of <-\> is restored back to <-\\>\\. (I can't see where <-\> actually occurs.) The fifth replacement deletes every occurrence of <->, resulting in the quoted version of the second half of the program being completely restored to an unquoted state. The sixth replacement replaces CT with *—somehow this results in the program containing an ever increasing number of asterisks. The seventh replacement seems to do the same thing as the second replacement.

Finally, following all seven replacements is the string RN, which is eventually replaced with a copy of the program, and everything starts over.

The end result is that the program outputs an infinite triangle of asterisks.

Details about all this can be found at the Esolang wiki page for ///.

Tanner Swett

Posted 2014-07-09T12:42:59.023

Reputation: 531

0

Shell

Let's not forget about the classic, only works in a script file:

#!/bin/sh
echo do something here
exec $0

Another one that also works on the command line, employing a signal handler recursively calling itself by unusual means:

trap 'echo "do something here"; kill -s USR1 $$' USR1; kill -s USR1 $$

A script file moving it's content into a new temporary file, sourcing itself and removing old temporary file:

#!/bin/sh
# Only remove tempfile previously created by ourselves
[ "$tempfile" -a -f "$tempfile" ] && rm -f "$tempfile"

echo 'do something here'

export tempfile=$(tempfile) || exit 1
cat "$0" >"$tempfile" || exit 1
. "$tempfile"

Franki

Posted 2014-07-09T12:42:59.023

Reputation: 81

0

JavaScript (ES6)

Small and smart.

+(a = {x:0,valueOf: ()=>(a.x++,+a)})

This code can be written like this:

a = {
    x: 0,
    valueOf: function() { 
        a.x++;
        a.valueOf();
    }
}
a.valueOf();

+(obj) tries to cast obj to number. It starts with calling obj.valueOf... And in this case, calling obj.valueOf results in an infinite loop, throwing stack overflow error.

Ginden

Posted 2014-07-09T12:42:59.023

Reputation: 197

0

Roblox Lua

More events.

local n=0
local m=Instance.new("Message",game.Workspace)

script.ChildAdded:connect(function(e)
    wait()
    local k
    k=e.AncestryChanged:connect(function()
        wait()
        k:disconnect()
        e.Parent=script
    end)
    m.Text="Hi! "..n
    n=n+1
    e.Parent=game.Workspace
end)
Instance.new("IntValue",script)

Creates an IntValue as a child of the current script and then uses events to endlessly move it back and forth between the script and the workspace while producing output via a Message instance.

SuperJedi224

Posted 2014-07-09T12:42:59.023

Reputation: 11 342

0

Java 8

Stream.iterate("Look @ me slurping ur cpu", i -> i).forEach(System.out::println);

Starts an infinite stream with a string, and each next element is the same as the previous: i -> i. The stream is consumed by printing each element to stdout.

Mark Jeronimus

Posted 2014-07-09T12:42:59.023

Reputation: 6 451

0

AutoIt

I golfed this (sue me :P). It just writes 0 to the console very, very slowly (and maxes out one CPU core along the way). Compile as a.exe.

Exit ConsoleWrite(0)+Run("a")

If you want to run this (and you probably shouldn't), use this to kill it:

While 1
    ProcessClose("a.exe")
Wend

mınxomaτ

Posted 2014-07-09T12:42:59.023

Reputation: 7 398

This IS recursion... – Mega Man – 2016-06-19T09:22:36.477

0

Standard C89, no extensions

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

int main(int argc, char **argv)
{
    jmp_buf b;
    int i = 0, j;

    if (argc > 1) i = atoi(argv[1]);
    if (i<=0) i = 10;

    j = setjmp(b);

    if (j<i) {
        printf("%d\n", j);
        longjmp(b, j+1);
    }
    return EXIT_SUCCESS;
}

Compiles cleanly with gcc -std=c89 -g -Wall -Wextra -pedantic.

Toby Speight

Posted 2014-07-09T12:42:59.023

Reputation: 5 058

0

C 42 bytes (w/single char return)

#include<stdio.h>
main(){printf("%9x",0);}

In this case, the printf is looping and printing up to 9 spaces to pad my hex output number 0. It is executing code (printing a space unless the output is filled) and looping (8 times in this case) without the usual loops. Tested on https://www.codechef.com/ide

Dave P.

Posted 2014-07-09T12:42:59.023

Reputation: 31

0

Molecule (v5.5+)

"lol!"~`q`n

Molecule has an built-in reflections system that allows code to be rewritten at runtime.

Output lol!, set the source code to the same one, which from v5.5 basically forces the interpreter to start reading from the start again.

user47018

Posted 2014-07-09T12:42:59.023

Reputation:

0

Python 2

class K(object):
    def __del__(self):
        print "You cannot stop the power of deallocators!"
        K()

This code goes into an infinite loop printing You cannot stop the power of deallocators.

Note that this does not work in Python 3

pppery

Posted 2014-07-09T12:42:59.023

Reputation: 3 987

0

Javascript ( 159 bytes )

This program relies on setInterval from javascript to iterate through an Enumerator (iterator). Uses a library I wrote to create an enumerator, and prints the value to the console

var e = _.Range(0,10).GetEnumerator();var id = setInterval(function(){var next = e.Next();if(next.Done){clearInterval(id);return;}console.log(next.Value);},1);

Image 1

applejacks01

Posted 2014-07-09T12:42:59.023

Reputation: 989

-1

VB6

Create a Timer on a form, set the Timer interval to 500

    Private Sub Timer1_Timer()
        Print "This is the lamest entry..."    
    End Sub

Although it will not show any more printing once the form is full, it will run until it is stopped.

DrDownload

Posted 2014-07-09T12:42:59.023

Reputation: 1

Can you fix the formatting? I tried to but apparently it's less than the minimum edit by other people. Just put 4 spaces before each line of code. – Brendan Long – 2014-07-11T12:33:27.690

-2

JavaScript

Array.foreach(function(item1, item2, ..){})

Array.prototype.foreach = function(callback) {

  var arr = this;
  var length = arr.length;
  var i = 0;
  var step = callback.length;
  
  function loopNext() {
    if (i < length) {
      loopBody();
    }
  }
  
  function loopBody() {
    callback.apply(arr, arr.slice(i,i+step));
    loopIncr();
  }
  
  function loopIncr() {
    i+=step;
    loopNext();
  }
  
  loopNext();
}


function testForeach() {
  var days = ['sun','Sunday',
              'mon','Monday',
              'tue','Tuesday',
              'wed','Wednesday',
              'thu','Thursday',
              'fri','Friday',
              'sat','Saturday'];

  var output = "";

  days.foreach(function(abbr, full) {
    output += full + '(' + abbr + '=' + this.indexOf(abbr) + ')\n';
  });

  document.getElementById('output').innerHTML = output;
}

testForeach();
<pre id="output"></pre>

wolfhammer

Posted 2014-07-09T12:42:59.023

Reputation: 1 219

Why the down votes? I followed the rules. The Array.forEach is functionality that I'm adding to JavaScript, not a built in function. It's like Tcl's foreach that can parameterize sets of values in a list. The array is flat but I'm iterating through it in a stride of 2 and naming the values abbr and full. – wolfhammer – 2015-09-17T10:24:15.967

x.foreach is an iterator, which is a loop, which is not allowed. – cat – 2016-01-04T15:03:31.387

@cat I created the foreach function without using loops or recursion in the function calling itself sense. – wolfhammer – 2016-01-04T19:29:39.363