Logo

Programming-Idioms

  • Fortran
  • Go

Idiom #272 Play FizzBuzz

Fizz buzz is a children's counting game, and a trivial programming task used to affirm that a programmer knows the basics of a language: loops, conditions and I/O.

The typical fizz buzz game is to count from 1 to 100, saying each number in turn. When the number is divisible by 3, instead say "Fizz". When the number is divisible by 5, instead say "Buzz". When the number is divisible by both 3 and 5, say "FizzBuzz"

import "fmt"
import "strconv"
for n:=1; n<=100; n++ {
	    out:=""
	    if n%3==0 {
		    out=out+"Fizz"
	    }
	    if n%5==0 {
		    out=out+"Buzz"
	    }
	    if out=="" {
		    out=out+strconv.Itoa(n)
	    }
	    fmt.Println(out)
    }
  integer :: i
  logical :: fizz, buzz
  do i=1,100
     fizz = mod(i,3) == 0
     buzz = mod(i,5) == 0
     if (fizz) write (*,'(A)',advance="no") 'Fizz'
     if (buzz) write (*,'(A)',advance="no") 'Buzz'
     if (.not. fizz .and. .not. buzz) write (*,'(I0)',advance="no") i
     write (*,'(A)',advance="no") ', '
  end do
  write (*,'()')
end program

Using non-advancing I/O to avoid starting on the next line.
for(int i = 1; i <= 100; i++)
{
    if((i % 15) == 0) std::cout << "FizzBuzz" << std::endl;
    else if((i % 5) == 0) std::cout << "Buzz" << std::endl;
    else if((i % 3) == 0) std::cout << "Fizz" << std::endl;
    else std::cout << i << std::endl;
}

New implementation...
< >
fizzbuzz