Tuesday, June 22, 2010

Java : FizzBuzz

I regularly read Jeff Atwood's blog and renewed my acquaintance for an old post: Why Can't Programmers.. Program?.

It talks about the Fizz-Buzz question i.e.

"Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". "

So I took up the challenge and knocked this out in Java using Netbeans in about 4 minutes.


for (int i = 1; i < 101; i++)
{
int j = i % 3;
int k = i % 5;
System.out.print("Number is " + i);
if (j == 0 && k == 0)
{
System.out.print(" FizzBuzz ");
}
else
{
if (j == 0)
System.out.print(" Fizz ");
if (k == 0)
System.out.print(" Buzz ");
}

System.out.println();
}


So there!

Enjoy!

No comments: