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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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