How to resolve the algorithm Towers of Hanoi step by step in the Fortran programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Towers of Hanoi step by step in the Fortran programming language

Table of Contents

Problem Statement

Solve the   Towers of Hanoi   problem with recursion.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Towers of Hanoi step by step in the Fortran programming language

Source code in the fortran programming language

PROGRAM TOWER
                             
  CALL Move(4, 1, 2, 3)
                
CONTAINS

  RECURSIVE SUBROUTINE Move(ndisks, from, to, via)
    INTEGER, INTENT (IN) :: ndisks, from, to, via
   
    IF (ndisks == 1) THEN
       WRITE(*, "(A,I1,A,I1)") "Move disk from pole ", from, " to pole ", to
    ELSE
       CALL Move(ndisks-1, from, via, to)
       CALL Move(1, from, to, via)
       CALL Move(ndisks-1, via, to, from)
    END IF
  END SUBROUTINE Move

END PROGRAM TOWER


PROGRAM TOWER2
 
  CALL Move(4, 1, 2, 3)
 
CONTAINS
 
  RECURSIVE SUBROUTINE Move(ndisks, from, via, to)
    INTEGER, INTENT (IN) :: ndisks, from, via, to
 
    IF (ndisks > 1) THEN
       CALL Move(ndisks-1, from, to, via)
       WRITE(*, "(A,I1,A,I1,A,I1)") "Move disk ", ndisks, "  from pole ", from, " to pole ", to
       Call Move(ndisks-1,via,from,to)
    ELSE
       WRITE(*, "(A,I1,A,I1,A,I1)") "Move disk ", ndisks, "  from pole ", from, " to pole ", to
    END IF
  END SUBROUTINE Move
 
END PROGRAM TOWER2


  

You may also check:How to resolve the algorithm Literals/Floating point step by step in the Oforth programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Pseudo-random numbers/Xorshift star step by step in the Julia programming language
You may also check:How to resolve the algorithm Largest proper divisor of n step by step in the Ada programming language
You may also check:How to resolve the algorithm Generic swap step by step in the Smalltalk programming language