×

Tower of Hanoi in C

What is Tower of Hanoi?

The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in Hanoi, Vietnam, which inspired the name of this puzzle game, was a place of worship.

Three rods and several discs make up the geometric puzzle known as The Tower of Hanoi. The discs are first arranged on a single rod in a cone-like tower structure, stacked one above the other in escalating order of size.

Rules

The goal of this challenge is to transfer the disc stack from the starting rod to another rod while adhering to the following guidelines:

  • A single disc can only be moved at once.
  • Every move involves taking the top disc from one stack and stacking it on top of another stack; a disc can only be moved if it is the top disc on a stack.
  • No disc should be stacked on top of another.

To transfer all of the discs from the leftmost rod to the rightmost rod is the objective. It takes steps to transfer n discs from one rod to another. In order to transfer three discs from the starting rod to the finishing rod, a total of 7 steps are needed. These steps are illustrated in below image:

Tower of Hanoi in C

 Recursive Method Approach

When a function is being executed in a system, recursion is the process through which the function calls itself. When using the recursion approach to address tiny issues, several considerations must be made.

We need to solve this Tower of Hanoi puzzle. Since it has three towers with the names P, Q, and R, the input for this puzzle is 3. This crossword's syntax will be as follows:

#include<stdio.h>
void Tower(int n,char a,char b,char c) {
   if(n>0) {
  	Tower(n-1,a,c,b);
  	printf("%c to %c\n",a,b);
  	Tower(n-1,c,b,a);
   }
}
int main() {
   int n=3;
   Tower(n,'P','Q','R');
}

Program Output

P to Q
P to R
Q to R
P to Q
R to P
R to Q
P to Q

A brief description of this methodology:

Let's use two discs as an illustration:
Tower 1 = 'P', Tower 2 = 'Q', Tower 3 = 'R'.
 
Step 1: Move the first disc from 'P' to 'Q'
Step 2: Move the second disc from 'P' to 'R'
Step 3: Move the first disc from 'Q' to 'R'
 
The pattern is as follows:
 
Transfer 'n-1' discs from 'P' to 'Q'.
Transfer the last disc from 'p' to 'R'.
Transfer 'n-1' discs from 'Q' to 'R'.

C code for the Tower of Hanoi:

#include <stdio.h>
void hanoitower(int n , char P , char R, char Q )
{
	if (n == 1)
	{
    	printf("\n Transfer disc 1 from Tower %c to Tower %c", P, R);
    	return;
	}
	hanoitower(n-1, P, Q, R);
	printf("\n Transfer disc %d from Tower %c to Tower %c", n, P, R);
	hanoitower(n-1, Q, R, P);
}
 
int main()
{
	int n = 4;
	hanoitower(n, 'P', 'R', 'Q'); 
	return 0;
}

Program Output :

 Transfer disc 1 from Tower P to Tower Q
 Transfer disc 2 from Tower P to Tower R
 Transfer disc 1 from Tower Q to Tower R
 Transfer disc 3 from Tower P to Tower Q
 Transfer disc 1 from Tower R to Tower P
 Transfer disc 2 from Tower R to Tower Q
 Transfer disc 1 from Tower P to Tower Q
 Transfer disc 4 from Tower P to Tower R
 Transfer disc 1 from Tower Q to Tower R
 Transfer disc 2 from Tower Q to Tower P
 Transfer disc 1 from Tower R to Tower P
 Transfer disc 3 from Tower Q to Tower R
 Transfer disc 1 from Tower P to Tower Q
 Transfer disc 2 from Tower P to Tower R
 Transfer disc 1 from Tower Q to Tower R

Code Explanation:

In order to start the recursive approach, we first set all the prerequisite information and command lines in C:

In the following line, we have used the Hanoi tower, which in C function, use as a Hanoi function, and void, which is used as the function return type. The function in the command below is stated as "P, Q, and R" because we need to move discs from P to R using Q.

void hanoitower(int n , char P , char R, char Q )

Following the creation of the functions to transfer a disc from P to R, hanoitower(n-1, P, Q, R); is used to move discs from P to Q using R. In these functions, n==1 is a Boolean expression that returns true if n is one and false if n is anything other than 1.

Finally, to move discs from Q to R using P, we utilized hanoitower(n-1, Q, R, P) In these routines, "n-1" denotes the movement of n discs from one tower to another.

 if (n == 1)
	{
    	printf("\n Transfer disc 1 from Tower %c to Tower %c", P, R);
    	return;
	}
	hanoitower(n-1, P, Q, R);
	printf("\n Transfer disc %d from Tower %c to Tower %c", n, P, R);
	hanoitower(n-1, Q, R, P);

This was a succinct explanation of the Tower of Hanoi's recursive approach in C, and we also included a detailed description of why it is necessary to swap the tower names' locations in codes in order to get the desired outcome.


Related Topics

Fibonacci series program in C using Recursion

In this tutorial, we’ll explore how to utilise recursion to build the Fibonacci sequence in C language. What does the term "Fibonacci Series" mean? The following number in a Fibonacci number series is...

2 minutes read.

Types of Array in C

What is an Array? One value can be stored in a variable at once. How many variables will you need if you have 100 values? Well, the answer isn't 100. It...

14 minutes read.

Call Back Function in Embedded C

Callback function are one the most remarkable systems in C. A callback function is any code that is passed as a contention to another code, so this is the last...

3 minutes read.

Booleans in C

Introduction to Boolean With all the complexities of programming, it can take time to understand the basics. One concept, in particular, that confuses many beginners is the use of Booleans in...

6 minutes read.

Execution flow of C program

There are various steps of the execution of the C program that is given below. The following step of the execution Write source codes Preprocess Compile Link edit Load Execute Editor or...

1 minute read.

Different ways to Declare the Variable as Constant in C

There are a wide range of ways of making the variable as steady Using const keyword: The const catchphrase permits a software engineer to inform the compiler that a specific variable should...

5 minutes read.

For loop in C Programming

In the C programming language, the for loop is used to repeatedly iterate over a set of instructions or a section of code. It is frequently used to traverse array-based...

3 minutes read.

GCD program in C

C language : Dennis Ritchie developed the general-purpose computer language C at Bell Laboratories in 1972. Despite being an ancient language, it is extremely popular. It is among the most widely used...

4 minutes read.

Purpose of a Function Prototype in C

A function prototype in C is a declaration of a function that specifies the function's name, return type and parameters. It has the following syntax: return_type function_name(parameter_list); For example, the prototype for...

4 minutes read.

Write a program that produces different results in C and C++

In this tutorial, we'll explore several programs that, depending on whether they are developed using C or C++ compilers, will produce varying outputs. There are numerous similar programs, but we will just...

2 minutes read.

Fahrenheit to Celsius in C

Before going into conversion, we have to know what Fahrenheit and Celsius mean, these are both units to measure the temperature.In our daily life, we use both Fahrenheit and Celsius,...

1 minute read.

C Array

An array is a collection of elements that are used to hold the fixed number of values of the same type. We cannot change the size and type of array...

2 minutes read.

Storage class in C

Storage class in C defines the scope, the visibility, and the lifetime of variables and functions. In other words, storage classes are used to describe the features of variables and...

3 minutes read.

Attributes in C

Attributes are one of modern C++ key features. It is the process by which initiator can add more information to the language instead of introducing new keywords for every attribute....

4 minutes read.

Character Set in C

Introduction Every language has some basic elements which are used to represent information. The English language includes alphabets which together shape a sentence, after which the sentences are used to shape...

3 minutes read.

Top Array Keywords in C

Sorting array in C Types of array in C Array of structure in C How do you initialize an array in C Array declaration in C Array of strings in C Multidimensional array in C Reverse array...

1 minute read.

Length of an Array Function in C

In C, there is no built-in function to get the length of an array. However, there are a few ways you can determine the length of an array. It is necessary...

15 minutes read.

Find Day from Day in C Without using function

Introduction: In the given article, I find daily in C without using functions. It takes 365 days for the earth to revolve around the sun. It will be close to...

3 minutes read.

Types Of Structures In C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

3 minutes read.

Add two numbers using the function in C

Here we will learn how to add two numbers by creating function in C. Let’s learn this with help of example. Code: - #include <stdio.h> int add_two_no(int a, int b); int main(){   int first_num,...

1 minute read.