Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
task :
move disks from source(s) to destination(d) using helper(h)

__ __ __

rules :
1.Only one disk can be moved at a time.
2.Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack. In other words, a disk can only be moved if it is the uppermost disk on a stack.
3.No larger disk may be placed on top of a smaller disk.

output the program gives :

transfer 1 from s to d
transfer 2 from s to h
transfer 1 from d to h -> shouldn't be there
transfer 3 from s to d
transfer 1 from h to s -> should come after next line, violates rule 2 places 2 before 1
transfer 2 from h to d
transfer 1 from s to d -> shouldn't be there

What I have tried:

video tutorial shows this program which give above output which is wrong

public class towerOfhanoi {
    public void toh(int n, String src, String helper, String destination) {
        if (n == 0) {
        toh(n - 1, src, destination, helper);
        System.out.println("transfer " + n + " from" + src + " to" + destination);
            toh(n - 1, helper, src, destination);

    public static void main(String[] args){
        int n=3;
        towerOfhanoi th = new towerOfhanoi();

can some one code for this output:

1 from s to d
2 from s to h
1 from d to h
3 from s to d
1 from h to s
2 from h to d
1 from s to d
Updated 7-Jan-23 5:28am
Richard MacCutchan 7-Jan-23 11:14am    
How about you do it yourself? There are only seven simple steps.
Shivam Siddharth 7-Jan-23 11:24am    
using recursion for eg step 2 in which value is 2 will also recurse for value 1 also which i don't want to happen and if i put a 'if' condition to stop that from happening step 3 won't be executed
how should i get the desired output

1 solution

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900