Clinton Montague

Developer, learner of things, functional programming enthusiast, hacker, and all round inquisitor.

Using a for loop, print the numbers from 0 to 5

March 16, 2009

I’ve been training for a ZCE certification, and found myself getting quite annoyed with some of the more obvious questions. One of the questions in the beginning of the test was which of the pieces of code would output the numbers 0 to 5 using a for loop. I mean, come on! I present some of my more creative and twisted ways of completing said task.

The obvious solution

So if you’re in an exam, the answer would be

but where’s the fun in that?! Below are various different ways of doing the same thing. They all work.
They’re all correct. They’re just not what you’d do.

Using an array

Outputting chars

Using a string to count

Using bitwise operators

The know it all method


What other ways can you think of to output the numbers 0 to 5 using a for loop?