Jump to content

Creating a loop singling out multiples of 3 and 5 and replacing them with a word


mitch3893

Recommended Posts

Hi,

 

I have recently been to an interview for a Junior PHP developer position and everything was going well until i was asked to do a task.

 

The task was as follows,

 

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

 

I could do the basic loop to print out the numbers but couldn't work out a way to single out the multiples of 3 and 5 and where the multiples were both 3 and 5.

 

Any help would be  appreciated.

 

Thanks

Dan

Link to comment
Share on other sites

This would do it:

<?php
for($i=1;$i<=100;++$i)
{
if($i % 3 == 0 && $i % 5 == 0)
	echo "FizzBuzz\r\n";
elseif($i % 3 == 0) // if remainder of i divided by 3 is 0 then i is a multiple of 3. See http://en.wikipedia.org/wiki/Modulo_operation
	echo "Fizz\r\n";
elseif($i % 5 == 0)
	echo "Buzz\r\n";
else
	echo $i . "\r\n";
}
?> 

 

You could probably do it a bit nicer than that but it's one way.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.