-2

I'm trying to write a Fizz Buzz script using a while loop to cycle through the numbers 1-100 and echo each one to the screen.

I'm using the modulus operator to find if a number is a multiple of:

  • 3 in which case it echos Fizz,
  • 5 in which case it echos Buzz,
  • or if its a multiple of both 3 and 5 it echos FizzBuzz

I've written the code below, tested all its parts and it seems to work, but when I run the script, it gets stuck in an infinite loop, echoing Fizz.

$i = 1;

while ($i <= 100) {

    if ((3 % $i) === 0) {
        echo 'Fizz';
        $i = $i++;
    } else if ((5 % $i) === 0) {    
        $i = $i++;
        echo 'Buzz';        
    } else if ( ((3 % $i) === 0) && ((5 % $i) === 0)){
        echo 'FizzBuzz';
    } else {
        echo $i++;
    }

}

Any idea were I went wrong?

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
sam
  • 9,486
  • 36
  • 109
  • 160
  • 1
    `$i % 3`. And you don't need the third and the fourth conditions – zerkms Jun 20 '13 at 20:58
  • Should this be tagged [tag:homework]? – cmbuckley Jun 20 '13 at 21:26
  • 2
    @cbuckley: http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated – zerkms Jun 20 '13 at 22:30
  • "My code doesn't work, where is the bug" style questions are seen as off topic. What have you tried? Where specifically are you stuck? What don't you understand. If you can distill that out, it will make both your experience and the overall communities experience better. But as it stands this question could use some improvement... – ircmaxell Jun 24 '13 at 02:33

1 Answers1

5
$i = 1;

while ($i <= 100) {

    $r = '';

    if ($i % 3 === 0) {
        $r .= 'Fizz';
    }

    if ($i % 5 === 0) {    
        $r .= 'Buzz';        
    }

    if (!$r) {
        $r = $i;
    }

    echo "$r\n";
    ++$i;
}

Online demo: http://ideone.com/WbXZEd

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • 1
    Can you **please** put some explanation into this answer? I know code-only answers are allowed, but come on. Who is this really helping? – ircmaxell Jun 24 '13 at 02:41
  • 1
    @ircmaxel: this answer contains only trivial operators and constructions. If OP cannot recognize any particular one - I'd be happy to explain one. But I won't explain what `=` and `<=` do - there is php manual for that. – zerkms Jun 24 '13 at 03:01
  • The prints incorrect result -- no numbers. Check this wiki http://c2.com/cgi/wiki?FizzBuzzTest – Omar Al-Ithawi Mar 09 '14 at 12:06
  • @omarithawi it produces the correct result. Please check the link provided in the answer. Thank you. – zerkms Mar 11 '14 at 03:37
  • @zerkms Sure, I did! Check **[this screenshot](http://oi57.tinypic.com/idg5j8.jpg)** your provided link it starts with `Fizz,Buzz`. While the **[correct FizzBuzz](http://ideone.com/dKqwzs)** starts with `1,2,Fizz,4,Buzz...`. Thank you – Omar Al-Ithawi Mar 11 '14 at 10:54