Loopy Loops

March 18, 2011

I don’t like this silly question. But it has appeared recently on Hacker News and Stack Overflow (C/C++ and Java, and probably other languages but I quit searching), and generated lots of comments on both, and it’s apparently a popular interview question, so we may as well do it here, too:

Print the numbers from 1 to 1000 without using any loop or conditional statements. Don’t just write the printf() or cout statement 1000 times.

Your task is to write the program in your favorite language. Have fun — think of as many solutions as you can, or the wackiest, or the fewest characters in the source file, or some other best-in-category. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Thanks, guys. I have now worked out a general system for
making any fixed number of repetitions of a transformation
(here, successor, with output) from zero, one, addition
and multiplication. The zero is a bit redundant. Here are
the building blocks.

To paraphrase a well-known programming quote, there are two ways of solving this exercise: write or program that obviously has no loops or conditionals, or write a program that has no obvious loops or conditionals. In the example below, I’ve chosen the latter :)

It’s based on lambda calculus and is written in Coffeescript rather than plain Javascript to keeps things slightly readable. It takes about 40 seconds to run in Chrome.

In C. No loops, conditionals, recursion, global variables or assignments; printf only called once (statically) and only 19 lines. (It’s actually shorter if you leave the macro out…) Undoubtedly the formatting will be screwy, but I see no ‘preview’ button here.