HiveBrain v1.2.0
Get Started
← Back to all entries
principleMinor

FizzBuzz vs. FortRan

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fortranfizzbuzzstackoverflow

Problem

In keeping with using FizzBuzz as an introduction to a language, I present FizzBuzz with a Fortran95 twist:

For multiples of 3, print Fort, and for 5's multiples print Ran. For multiples of both, print FortRan.

Looking especially for style and common practice criticisms. A hint on how to left-justify the values in a standard way would be appreciated too.

The following code is presented in Ideone too:

program fizzbuzz
implicit none
integer ::i

! Loop through integers 1 through 100
! Multiples of 3 print Fort
! Multiples of 5 print Ran
! Multiples of both print FortRan
! 15 is the lowest common multiple of 3, and 5
!    and thus is a shortcut to FortRan

do i=1,100
    if (MODULO(i, 15) == 0) then
        write (*,'(A8)') 'FortRan'
    else if (MODULO(i, 3) == 0) then
        write (*,'(A8)') 'Fort'
    else if (MODULO(i, 5) == 0) then
        write (*,'(A8)') 'Ran'
    else
        write (*,'(I8)') i
    end if
end do

end program fizzbuzz

Solution

I find MODULO() to be jarring, when everything else is written in lowercase. Be consistent.

To left-justify strings in the output, write it using a * format. Since you want to write to standard output, you can simplify it by using print instead.

To left-justify numbers in the output, first convert it to a string, then strip leading spaces.

program fizzbuzz
implicit none
integer ::i
character(len=8) :: str

! Loop through integers 1 through 100
! Multiples of 3 print Fort
! Multiples of 5 print Ran
! Multiples of both print FortRan
! 15 is the lowest common multiple of 3, and 5
!    and thus is a shortcut to FortRan

do i=1,100
    if (modulo(i, 15) == 0) then
        print *, 'FortRan'
    else if (modulo(i, 3) == 0) then
        print *, 'Fort'
    else if (modulo(i, 5) == 0) then
        print *, 'Ran'
    else
        write (str, '(i8)') i
        str = adjustl(str)
        print *, str
    end if
end do

end program fizzbuzz

Code Snippets

program fizzbuzz
implicit none
integer ::i
character(len=8) :: str

! Loop through integers 1 through 100
! Multiples of 3 print Fort
! Multiples of 5 print Ran
! Multiples of both print FortRan
! 15 is the lowest common multiple of 3, and 5
!    and thus is a shortcut to FortRan

do i=1,100
    if (modulo(i, 15) == 0) then
        print *, 'FortRan'
    else if (modulo(i, 3) == 0) then
        print *, 'Fort'
    else if (modulo(i, 5) == 0) then
        print *, 'Ran'
    else
        write (str, '(i8)') i
        str = adjustl(str)
        print *, str
    end if
end do

end program fizzbuzz

Context

StackExchange Code Review Q#62702, answer score: 4

Revisions (0)

No revisions yet.