Fortran 95 Do-While Loop Not Exiting on False Condition

jdawg picture jdawg · Feb 28, 2011 · Viewed 12.2k times · Source

Here is my code:

program change 

            integer:: amount, remainder, q, d, n, p
            amount = 47
            remainder = amount
            print*,remainder
            q = 0
            d = 0
            n = 0
            p = 0

            do while (remainder >= 25)
                    remainder = remainder - 25
                    print*,remainder
                    q = q + 1       
            end do
            do while (remainder >= 10)
                    remainder = remainder - 25
                    print*,remainder
                    d = d + 1       
            end do
            do while (remainder >= 5)
                    remainder = remainder - 25
                    print*,remainder
                    n = n + 1       
            end do
            do while (remainder >= 1)
                    remainder = remainder - 25
                    print*,remainder
                    p = p + 1       
            end do 

            print*, "# Quarters:", q
            print*, "# Dimes:", d
            print*, "# Nickels:", n
            print*, "# Pennies:", p

    end program change

Output:

 47
      22
      -3
# Quarters:           1
# Dimes:           1
# Nickels:           0
# Pennies:           0

The first loop (>=25) should exit once the remainder becomes 22, but it runs through once more and yields a negative number. Why is this not exiting even though the condition is false? I'm using IDEone.com's Fortran "compiler" which appears to be Fortran 95-like.

Answer

brady picture brady · Feb 28, 2011

Your DO loops are fine. You simply need to subtract the correct denomination from remainder in each loop. For instance change your second DO loop to:

        do while (remainder >= 10)
                remainder = remainder - 10
                print*,remainder
                d = d + 1       
        end do

and change the rest in a similar manner.