×

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

Branching Statements in C

What is branching in c? Branching gets its name from the fact that the computer can select which branch to follow.Programs written in the C language execute statements one after the...

6 minutes read.

Ftell() Function in C

Ftell(): In File Handling we have some special functions like Ftell(), Fseek(), rewind() etc.. while you are randomly accessing the file these functions play very important role and these functions...

3 minutes read.

Function in C

Function is a group of statements that are used to perform any task. In other words, we can say that a function is a self- contained a block of programs...

3 minutes read.

Type qualifiers in C

Type qualifiers in C: In the C programming language, type qualifiers are the keywords that prepend to the variables to change their accessibility, i.e., we can tell that the type...

4 minutes read.

C printf and Scanf

Input-Output functions in C Programming In C Language, the printf() and scanf() are inbuilt library functions that used for input and output. It is defined in the header file“<stdio.h>”. printf() Function: In C...

2 minutes read.

getc() function in C

Getc is one of the file handling technique in C. The Getc() is a C library function gets the next character or new characters  from the specific stream and supports...

4 minutes read.

Pointers in C

Pointers in C: In the C programming language, a pointer is a pointer variable that points to the address of the other variable. It also stores the address of the...

4 minutes read.

DSA Program in C

How is a Data Structure Implemented? The foundational terms of a data structure are the following terms. Data may be arranged using data structures to make it easier to use. Each data...

20 minutes read.

Stack implementation in C

Stack implementation in C Stack stores the data in a particular order. It is a linear data structure that follows the principle of the Last In First Out (LIFO) technique where...

3 minutes read.

Entry Control Loop in C

Initially, an entry control loop verifies the termination condition at the entry point. After that, its control passes to the main body of the while or for loop if the...

3 minutes read.

How to delete a file in C

A file is a group of data kept on a secondary device, such as a hard disc. It is typically utilized as a real-world application with a lot of data. These...

3 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Quick sort in C

Quick-sort, in the same way, like a merge sort, follows the principle of the divide and conquer algorithm. It then picks an element as pivot and partitions, and the given...

4 minutes read.

File Operations in C

Why do I need the file? All data will be lost when the program exits. Saving data to a file keeps it safe even if the program stops working. If there...

6 minutes read.

Bubble sort in C

Bubble sort in C Bubble sort is defined as the algorithm that is used for the sorting mechanism. It follows the technique of replacing the first index with the more minor...

4 minutes read.

Malloc function in C

When the user or programmer does not know how much memory space is needed in the application, it a needs dynamic memory allocation during runtime. Dynamic memory allocation helps us to...

4 minutes read.

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.

Formatted Input and output function in C

Formatted I/O functions display multiple outputs to the user by taking various inputs. All data types like int, float, char and double are supported by the formatted I/O function. In...

4 minutes read.

While Loop Syntax in C

What is Loop? The statements in the sequence are repeatedly executed via looping statements in C until the condition is met. The body of a loop and a control statement make...

4 minutes read.

C Programming Tutorial

What is C Programming C is most popular and widely used computer programming language. It was developed by Dennis Ritchie in 1972 at the Bell Lab. It is used to develop system application software. There...

8 minutes read.