ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

VB.Net program to implement the Tower of Hanoi problem

Here, we are going to learn how to implement the Tower of Hanoi problem in VB.Net?
Submitted by Nidhi, on January 18, 2021

Here, we will implement the Tower of Hanoi problem using recursion.

Program/Source Code:

The source code to implement the Tower of Hanoi problem is given below. The given program is compiled and executed successfully.

'VB.Net program to implement the Tower of Hanoi problem.

Imports System

Module Module1
    Class TOH
        Private discs As Integer

        Public Sub New(ByVal val As Integer)
            discs = val
        End Sub

        Public Sub MoveDiscs(ByVal num As Integer, ByVal from As Integer, ByVal tto As Integer, ByVal other As Integer)
            If (num > 0) Then
                MoveDiscs(num - 1, from, other, tto)
                Console.WriteLine("Move disk {0} from tower {1} to tower {2}", num, from, tto)
                MoveDiscs(num - 1, other, tto, from)
            End If
        End Sub
    End Class

    Sub Main()
        Dim T As TOH
        Dim total_discs As Integer

        Console.Write("Enter the total number of discs: ")
        total_discs = Integer.Parse(Console.ReadLine())

        T = New TOH(total_discs)
        T.MoveDiscs(total_discs, 1, 3, 2)
    End Sub
End Module

Output:

Enter the total number of discs: 3
Move disk 1 from tower 1 to tower 3
Move disk 2 from tower 1 to tower 2
Move disk 1 from tower 3 to tower 2
Move disk 3 from tower 1 to tower 3
Move disk 1 from tower 2 to tower 1
Move disk 2 from tower 2 to tower 3
Move disk 1 from tower 1 to tower 3
Press any key to continue . . .

Explanation:

In the above program, we created a module Module1 that contains TOH class and Main() function.

The TOH class contains a parameterized constructor and MoveDiscs() method. Here, parameterized constructor is used to initialized with the number of discs. The MoveDiscs() method is a recursive method, which is used to move the disc according to the Tower of Hanoi problem.

The Main() function is the entry point for the program, Here, we created the object of TOH class and read the number of discs from the user, and print discs movement on the console screen.

VB.Net Data Structure Programs »

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.