mitch3893 Posted April 15, 2011 Share Posted April 15, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/233817-creating-a-loop-singling-out-multiples-of-3-and-5-and-replacing-them-with-a-word/ Share on other sites More sharing options...
analog Posted April 15, 2011 Share Posted April 15, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/233817-creating-a-loop-singling-out-multiples-of-3-and-5-and-replacing-them-with-a-word/#findComment-1202024 Share on other sites More sharing options...
mitch3893 Posted April 15, 2011 Author Share Posted April 15, 2011 Thats great thanks a lot (I dont quite understand it all yet but will try to get my head around it) Quote Link to comment https://forums.phpfreaks.com/topic/233817-creating-a-loop-singling-out-multiples-of-3-and-5-and-replacing-them-with-a-word/#findComment-1202028 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.