This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.

Hi guys this is a small program abt Tower of Hanoi...(if u don't wat the prblem is plz mail me I'll give the explanation for tower of Hanoi) But my real worry is when the same logic is tried in 'C' the program works fine for recursion... But when it is implemented in java..O/p is terribly out of place..Can u plz suggest ways to achieve the result??? I am including the code here... TIA ravi class TowerOfHanoi { void tower(int n, char a, char b, char c) { // this is a recursive function which calls itself if (n>0) { tower(n-1,'a','c','b'); System.out.println("Move disk "+n+" from "+ a +" to "+ b +" via "+c); tower(n-1,'c','b','a'); } } public static void main(String args[]) { tower(3,'a','b','c'); } }

What's this program meant to do? I copied it, then just changed a couple of things so I could compile it as a C++ console app, but just gives me the following when its executed:

Move disk 1 from a to c via b Move disk 2 from a to c via b Move disk 1 from c to b via a Move disk 3 from a to b via c Move disk 1 from a to c via b Move disk 2 from c to b via a Move disk 1 from c to b via a

Have I done something wrong while trying to convert it myself or am I just too much of a newbie in Java to know what the heck i'm doing with this... BTW What's the Tower of hanoi?

<i>I'm currently reading 'How to program Java' by Deitel</i><br /><b>I am still learning, so be kind. I also know C++, by the way</b>

Ravi Sathish
Ranch Hand

Joined: Feb 26, 2002
Posts: 131

posted

0

Hey tower of hanoi is a old puzzle... here u have disks('n' no.. of them)on pole a.. of different sizes arranged from biggest one(highest number here 3) at the bottom to smallest one(lower number here 1)at the top... the solution is to move the disks from pole a to pole b using c as an intermediate pole.. any number of moves is allowed but always a smaller disk should be on top of the bigger disk.. hope this helps...