Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
1  
What is the definition of a loop? –  CousinCocaine yesterday
1  
As the existing comments and answers demonstrate, it's not clear what is covered by the "etc." in the forbidden structures. –  Peter Taylor yesterday
2  
For 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 23 hours ago
1  
"Changed to popularity contest for a focus on creativity" Changing the question is cheating! –  CousinCocaine 23 hours ago
1  
@CailinP a winning answer is not a winning answer anymore. That is changing the outcome by changing the question. –  CousinCocaine 22 hours ago
show 16 more comments

38 Answers

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.

share|improve this answer
    
Why does it end? –  TheRare 18 hours ago
1  
It eventually hits "also", which is defined, and therefore not missing. –  histocrat 18 hours ago
    
Ah, now I see it. Somehow missed the last line. Nice one, have a plus one. –  TheRare 18 hours ago
4  
This is hysterical. –  Michael B 16 hours ago
1  
@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 ruby-doc.org/core-2.1.2/String.html#method-i-next –  3Doubloons 13 hours ago
show 3 more comments

Python - 16

or any other language with eval.

exec"print 1;"*9
share|improve this answer
    
Can you describe what your program does? –  CailinP yesterday
5  
It 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 21 hours ago
2  
Yay for string multiplication! –  Thane Brimhall 17 hours ago
add comment

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: http://stackoverflow.com/questions/24662454/how-does-a-garbage-collector-avoid-an-infinite-loop-here

share|improve this answer
4  
I didn't even know C# had destructors. +1 for teaching me. –  TheRare 18 hours ago
    
@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 18 hours ago
    
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 16 hours ago
    
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 16 hours ago
    
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 16 hours ago
show 3 more comments

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.

share|improve this answer
    
Can you explain it a bit more? What exactly is it doing? –  CailinP yesterday
    
execv() executes the file named by the first argument. Since v[0] is the name of this executable, it executes itself again. –  kwokkie yesterday
    
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 yesterday
3  
@mniip Tail recursion, then, if it applied at the process level –  Izkata 12 hours ago
1  
@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 11 hours ago
show 3 more comments

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
$ 
share|improve this answer
1  
nice! I wonder why those functions aren't part of the C spec? ;-D –  Brian Minton 18 hours ago
1  
@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 ;-) –  DigitalTrauma 17 hours ago
add comment

Bash, 3 characters

yes

yes will repeatedly return 'y' to the console

Edit: Everyone is encouraged to edit this line:

yes "10\n 20 GOTO 10"
share|improve this answer
    
Why will this keep running? im not questioning it just trying to figure out why. –  Teun Pronk yesterday
    
@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 yesterday
    
More fun would be to use yes to keep some other loop going. –  trlkly 15 hours ago
1  
don't forget that yes can take an argument to print something other than 'y' –  Sparr 12 hours ago
    
@trlkly yes | while read VAL; do ...;done - except while isn't allowed =P –  Izkata 12 hours ago
show 1 more comment

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

share|improve this answer
1  
This is pretty evil for sure ;) –  CailinP 19 hours ago
add comment

Befunge

.

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

share|improve this answer
    
Ha! I love tricks like this –  CailinP 16 hours ago
add comment

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.

share|improve this answer
add comment

JS

Not very original but small. 20 chars.

setInterval(alert,1)
share|improve this answer
add comment

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 try.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;
  });
}
share|improve this answer
1  
The Y combinator? –  aditsu 20 hours ago
    
Technically, 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 8 hours ago
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
1  
I 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. –  TheRare 22 hours ago
2  
fix(print"">>), this also involves no explicitly named repetition functions. –  mniip 21 hours ago
    
@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 20 hours ago
    
@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 20 hours ago
    
@proudhaskeller It's the same in clojure. –  TheRare 19 hours ago
show 2 more comments

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');
?>
share|improve this answer
    
Darn, this counts as recursion as well, doesn't it? –  Pichan 15 hours ago
    
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. –  eithedog 4 hours ago
add comment

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);}
share|improve this answer
    
It's still recursive, you're just doing it with two alternate layers. –  scragar 21 hours ago
3  
@scragar: OP defined a recursive function as a function that calls itself, neither f nor g calls itself. –  Kyle Kanos 21 hours ago
    
The term for this is 'mutual recursion'. –  user19057 16 hours ago
    
The first solution doesn't compile. You have to forward declare g() (and in the second too). –  clcto 15 hours ago
    
@clcto: works fine for me. What compiler are you using? –  Kyle Kanos 15 hours ago
show 2 more comments

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

share|improve this answer
add comment

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.

share|improve this answer
    
+1 for the picture, plus you did this in assembly! –  CailinP 1 hour ago
add comment

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

share|improve this answer
add comment

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

share|improve this answer
add comment

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.

share|improve this answer
add comment

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)))
share|improve this answer
add comment

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>
share|improve this answer
    
Don'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. –  eithedog 4 hours ago
add comment

Java

Let's play with Java class loader:

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.

share|improve this answer
add comment

Java

The following code contains no recursive function (even no mutually recursive functions), no looping primitive and doesn't call any built-in function, yet it allows to repeat a given action arbitrary times (in this example prints "Hello world!" 100-times):

abstract class Strange<A> {
    public abstract A f(Strange<A> s);

    public final A extract() {
        return this.f(this);
    }
}

public class Main {
    /** Print "Hello world" 100-times. */
    public static void main(String argv[]) {
        new Strange<Void>() {
            int count = 100;

            public Void f(Strange<Void> r) {
                if (count-- > 0) {
                    System.out.println("Hello world!");
                    r.extract();
                }
                return null;
            }
        }.extract();
    }
}

Explanation: The trick is in the class Strange. It is a recursive data type that consumes itself, which, as shown in the example, allows arbitrary repetition. Function f, as implemented in main, doesn't call any function on this (just extract on its argument), so it's not recursive and neither is the combination f and extract. The recursion is hidden just in the data type - by passing this to f in extract, we can induce a nested call to f.

Such a data type allows to construct a fixed-point combinator, which in turn allows to implement arbitrary recursive algorithm, without using any recursive definitions.

This is even more succinctly described in Haskell:

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

Again, there is neither a recursive function defined nor used (from some existing library).

share|improve this answer
    
a calls b which calls a, thats recursion. You even get it stashed upon your stack. –  Angelo Neuschitzer 5 mins ago
add comment

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--); }
   }
share|improve this answer
    
I 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 17 hours ago
    
How does it not count? There is no loop and no recursion. –  LVBen 17 hours ago
    
Also, the call stack is not anywhere near massive unless maybe you consider a 32 calls high to be massive. –  LVBen 17 hours ago
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment
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...

share|improve this answer
add comment

Python

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
share|improve this answer
add comment

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();
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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