Comp Sci What is the error in my Towers of Hanoi Fortran 90 program using recursion?

  • Thread starter Thread starter Dylicious
  • Start date Start date
  • Tags Tags
    Fortran
AI Thread Summary
The Fortran 90 Towers of Hanoi program compiles but produces incorrect output due to uninitialized variables for 'source' and 'dest'. When the program runs, it displays garbage values instead of the expected peg labels. The recursive subroutine MoveTower is correctly structured, but the lack of initialization leads to unpredictable behavior. To resolve the issue, ensure that 'source', 'dest', and 'spare' are properly assigned before use. Addressing this will correct the program's functionality and output.
Dylicious
Messages
5
Reaction score
0

Homework Statement


Write a Towers of Hanoi program in Fortran 90 using a subroutine.


Homework Equations





The Attempt at a Solution


hello all

Ive been trying to write a simple Towers of Hanoi problem in FORTRAN 90 dealing with recursion.
Ive got my program to compile but it doesn't do the right thing, if you know the Towers of Hanoi problem than you'll understand why, what I need is someone to show me where I went wrong in my code. Ill post the code I wrote as well as what happens when I run it. THanks again guys!

Program Hanoi
! A Program for generating the sequence of moves to play the Towers of Hanoi game.
! Filename: Hanoi.f90 Src: ESS 22/09/2003
Implicit NONE
INTEGER :: n
character (len=1) :: A='A',B='B',C='C'

Interface
recursive subroutine MoveTower( n, source, dest, spare)
Implicit NONE
integer, intent(in) :: n
character (len=1) :: source, dest, spare
end subroutine MoveTower
End Interface

print *,'n: '
read *,n

! Check validity of input

IF (n <= 0) THEN
print *,'Invalid Input, n must be positive'
STOP
End IF

call MoveTower(n,A,B,C)
end Program Hanoi

Recursive Subroutine MoveTower( n, source, dest, spare)
IF (n == 1) THEN
print *,'Move disk 1 from source peg to destination peg'
ELSE
call MoveTower( n-1, source, spare, dest)
print *,'Move disk ',n,'from peg ',source,'to peg ',dest
call MoveTower( n-1, spare, dest, source)
END IF
RETURN
END Subroutine MoveTower


Heres what happens when I run it...

Hanoi
n:
3
Move disk 1 from source peg to destination peg
Move disk 2 from peg 9.1084400E-44 to peg 9.3886997E-44
Move disk 1 from source peg to destination peg
Move disk 3 from peg 9.1084400E-44 to peg 9.2485699E-44
Move disk 1 from source peg to destination peg
Move disk 2 from peg 9.3886997E-44 to peg 9.2485699E-44
Move disk 1 from source peg to destination peg


any ideas??
Ps Happy Thanksgiving if you're awesome!
 
Physics news on Phys.org
Variables 'source' and 'dest' are never initialized nor set equal to any value.
 
Garbage values as in the following line are usually an indication that a variable was used before it was initialized.

Move disk 2 from peg 9.1084400E-44 to peg 9.3886997E-44
 

Similar threads

Back
Top