tower-of-hanoi-in-c

“`html

The Tower of Hanoi puzzle stands as a timeless illustration of recursion, particularly when executed in the C programming language. It merges mathematics, reasoning, and programming concepts, aiding in the comprehension of recursion.

In this article, we will explore what the Tower of Hanoi challenge entails, and we will develop a solution using the C programming language. Additionally, we will scrutinize the mathematical reasoning and complexity associated with the Tower of Hanoi as well as its real-world applications.

Contents Overview:

What is the Tower of Hanoi?

The Tower of Hanoi is a traditional mathematical conundrum that entails relocating a stack of discs from one rod (tower) to another, adhering to a defined pattern. The objective is to transfer the entire stack of discs from one rod to another. This process recursively continues until the stack of discs is successfully moved from one rod to the other. There are three towers: the origin tower, housing the discs; the auxiliary tower, serving as a temporary holding area for the discs; and the destination tower, which acts as the final resting place for the discs.

Tower of Hanoi problem by a diagram

What is the Challenge of the Tower of Hanoi?

Let’s elucidate the Tower of Hanoi challenge with a visual aid:

Tower of Hanoi starting

As depicted in the above illustration, we observe three towers. One of them is stacked with n discs of various sizes arranged in descending order (the largest disc is at the base, while the smallest disc is at the top). The goal of this challenge is to transfer all the discs from the origin tower to the destination tower utilizing a third tower, without altering the sequence of the discs. According to the rules, only one disc may be moved at a time.

Wrong Tower of Hanoi

The preceding image illustrates an incorrect arrangement, even though all discs are relocated to the destination tower, as the order of the discs is incorrect.

Tower of Hanoi final

This represents the proper solution to the Tower of Hanoi.

C Programming Certification Course
Elevate your tech career with C – Enroll today!
quiz-icon

Why is the Tower of Hanoi significant in computer science and recursion?

The Tower of Hanoi holds a pivotal role in computer science, serving as a straightforward and elegant demonstration of recursion, which is a potent problem-solving strategy where a function invokes itself on smaller segments of the same problem. It aptly illustrates the “divide and conquer algorithm,” whereby intricate problems are simplified into smaller subproblems.

Significance of the Tower of Hanoi

Outlined below are the reasons why the Tower of Hanoi is noteworthy:

  • Divide and Conquer – It exemplifies the divide and conquer strategy by partitioning the task of moving n discs into smaller tasks of relocating n-1 discs. This technique proves to be more effective than addressing the entire issue simultaneously for a considerable number of discs.
  • Recursion – The Tower of Hanoi serves as an excellent representation of recursion. To shift a stack of n discs, we recursively transfer n-1 discs from the origin tower to an intermediary tower, followed by moving the largest disc directly to the destination tower. Ultimately, the n-1 discs will be moved from the intermediate tower to the destination tower. This procedure is repeated until all discs have reached the destination tower in the correct order (with the largest disc at the bottom and the smallest at the top).
  • Algorithm Analysis – The Tower of Hanoi demonstrates how algorithm complexity increases exponentially, possessing an exponential time complexity of O(2^n) and a space complexity of O(n).

Historical Context and the Tower of Hanoi

The Tower of Hanoi was created by French mathematician Édouard Lucas in 1883. According to folklore, in a Hindu temple in Kashi Vishwanath, India, priests were tasked with moving 64 golden discs among three poles, adhering to specific regulations. Although the priests suggested that it was of ancient origin, the puzzle itself is relatively modern and was invented by Lucas. Lucas may have drawn inspiration from a similar game encountered in Vietnam, a French…

“““html

colony during that period, which was renamed the Tower of Hanoi. This challenge consists of relocating n discs of various dimensions from one pole to another, adhering to the guideline that the largest disc must be positioned below while the smallest disc sits atop. In the realm of computer science, it serves to demonstrate recursion and data structures.

What is the Solution to the Tower of Hanoi in C?

The Tower of Hanoi can predominantly be resolved using recursion. Its primary aim is to transfer all the discs from the starting tower to the target tower without altering their sequence; specifically, the largest disc will rest at the base, while the smallest disc will sit at the top. A larger disc is not permitted to be placed on a smaller one. It follows the principle that only a single disc may be moved at any given time.

1. Solution to the Tower of Hanoi Using Recursion

Let’s explore the Tower of Hanoi challenge in C programming via recursion. Recursion refers to a function that invokes itself to address a smaller segment of the problem. Below is the code illustrating a recursive example in C for the Tower of Hanoi.

C

Code Copied!

var isMobile = window.innerWidth “);

editor10715.setValue(decodedContent); editor10715.clearSelection(); editor10715.setOptions({ maxLines: Infinity });

function decodeHTML10715(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

function copyCodeToClipboard10715() { const code = editor10715.getValue(); navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor10715 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor10715 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode10715() { var code = editor10715.getSession().getValue();

jQuery(“#runBtn10715 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”, data: { language: “c”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output10715”).html(“

"+data+"

“); jQuery(“.maineditor10715 .code-editor-output”).show(); jQuery(“#runBtn10715 i.run-code”).hide(); } }); }

function closeoutput10715() { jQuery(“.maineditor10715 .code-editor-output”).hide(); }

// Attach event listeners to the buttons document.getElementById(“copyBtn10715”).addEventListener(“click”, copyCodeToClipboard10715); document.getElementById(“runBtn10715”).addEventListener(“click”, runCode10715); document.getElementById(“closeoutputBtn10715”).addEventListener(“click”, closeoutput10715);

Output

Tower of Hanoi using Recursion

In this recursive implementation, the function invokes itself to relocate n-1 discs prior to and following the movement of the nth disc.

2. Solution to the Tower of Hanoi Using the Iterative Method

Let’s examine the C programming utilizing iteration to address the Tower of Hanoi. Iteration entails repeating a specific set of instructions until a designated condition is fulfilled. As we adopt iteration rather than recursion, bitwise logic is applied. This aids in transferring the discs from the source tower to the target tower by adhering to specific rules.

C

Code Copied!

“““html

var isMobile = window.innerWidth “);

editor11489.setValue(decodedContent); // Initialize the default text editor11489.clearSelection();

editor11489.setOptions({ maxLines: Infinity });

function decodeHTML11489(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard11489() { const code = editor11489.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert(“Code copied to clipboard!”);

jQuery(“.maineditor11489 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor11489 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error duplicating code: “, err); }); }

function runCode11489() {

var code = editor11489.getSession().getValue();

jQuery(“#runBtn11489 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”,

data: { language: “c”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output11489”).html(“

"+data+"");
									jQuery(".maineditor11489 .code-editor-output").show();
									jQuery("#runBtn11489 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function closeoutput11489() {	
		var code = editor11489.getSession().getValue();
		jQuery(".maineditor11489 .code-editor-output").hide();
		}

    // Attach event listeners to the buttons
    document.getElementById("copyBtn11489").addEventListener("click", copyCodeToClipboard11489);
    document.getElementById("runBtn11489").addEventListener("click", runCode11489);
    document.getElementById("closeoutputBtn11489").addEventListener("click", closeoutput11489);
 
    



Output

Tower of Hanoi using iteration

In this iterative version, disc motions are demonstrated step-by-step using a loop and bitwise techniques without recursion.

Solving Tower of Hanoi

Mathematical Analysis: Minimum Moves Required

In the Tower of Hanoi, the least number of moves necessary to resolve the issue for n discs is represented by the equation

Minimum Moves = 2ⁿ − 1,

where n denotes the quantity of discs.

Time Complexity

As the number of discs increases, the amount of recursive calls grows exponentially, and each of these calls produces two nested calls until the base case is achieved. The time complexity of the Tower of Hanoi stands at O(2^n).

Space Complexity

Since each level invokes the next level once, the maximum depth of the recursion stack is n. The space complexity of the Tower of Hanoi is O(n).

Practical Applications of the Tower of Hanoi

Here are several real-world applications of the Tower of Hanoi:

  1. Recursion and Algorithm – The Tower of Hanoi challenge serves as a classic example to teach recursion; it applies the divide and conquer strategy, dividing the large issue into smaller subproblems.
  2. Problem-Solving Studies – To analyze human problem-solving abilities, it can be utilized in psychological examinations.
  3. Resource Management – The effective transfer of discs from one tower to another can be analogous to optimizing logistics and resource distribution in various real-world contexts.
  4. Mathematical Research – In mathematics, the Tower of Hanoi is employed to explore the concept of recursion, illustrating a compelling instance of recursion.
  5. Data Structures – It provides an insightful example of stack operations, including push and pop, and demonstrates how data can be managed in an organized manner.
Free Course on C Programming and DSA
Learn C Without Cost – Begin Coding!
quiz-icon

Conclusion

In this article, we have examined the Tower of Hanoi dilemma, grasped its recursive and iterative resolutions in C, and evaluated its time and space complexities. This challenge not only enhances our understanding of recursion but also fortifies our problem-solving abilities, rendering it an essential concept for C developers.

Tower of Hanoi in C – FAQs

1. What is the purpose of the Tower of Hanoi?

The Tower of Hanoi comprises three pegs with n discs on the initial peg. The aim of the challenge is to relocate all the discs from the initial peg to the target peg utilizing the auxiliary peg while maintaining the order that the largest disc is at the base and the smallest at the top.

2. What are the time and space complexities of Tower of Hanoi?

The space complexity for the Tower of Hanoi is O(n), while the time complexity is O(2n).

3. Which algorithm is utilized in Tower of Hanoi?

The approach applied in the Tower of Hanoi is recursion. It serves as an excellent example of the “divide and conquer” method, as it decomposes the problem into smaller subproblems to solve it in a more efficient manner.

4. What is the minimal number of moves necessary to complete the Tower of Hanoi?

The least number of moves needed to resolve the Tower of Hanoi is
2n – 1, where n = the number of discs.

5. Are there any practical applications of the Tower of Hanoi?

Indeed, there are several real-world applications of the Tower of Hanoi. Examples include cognitive psychology evaluations, sequencing for robotic arms, data backup and restoration systems, file organization and sorting, as well as recursive algorithm formulation.

The post Tower of Hanoi in C appeared first on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This