body, html { width: 100%; height: 100%; } body{ padding-top:100px; } body, h1, h2, h3, h4, h5, h6 { font-family: "Lato","Helvetica Neue",Helvetica,Arial,sans-serif; font-weight: 700; } #content{ min-height: 600px; } #banner_image { padding-bottom: 50px; text-align: center; color: #f8f8f8; background: url(../img/intro-bg_1.jpg) no-repeat center center; background-size: cover; } #banner_content { position: relative; padding-top: 6%; padding-bottom: 6%; margin-top: 12%; margin-bottom: 12%; background-color: rgba(0, 0, 0, 0.7); max-width: 660px; } #item_list { padding-top: 50px; } /*This code ensures that when we navigate to a particular section of a page, the section does not get lost behind the header*/ #cameras:before, #watches:before, #shirts:before{ display: block; content: " "; margin-top: -85px; height: 85px; visibility: hidden; } #login-panel .panel-footer{ font-weight:normal; } footer { padding: 10px 0; background-color: #101010; color:#9d9d9d; bottom: 0; width: 100%; } .red{ color:red; } #settings-container{ margin-bottom:10px; } .navbar-brand{ font-size:20px; } @media(max-width:768px) { #banner_content { padding-bottom: 15%; } footer{ text-align:left; } } .remove_item_link{ color:#0000ff; }

Tower of Hanoi in C

Tower Of Hanoi is a classic problem of Recursion. So this problem really gives you the insights of Recursion and how well it works in these problems.
Recursion is applied to problems that have the Optimal substructure property.
And the Tower of Hanoi problem also follows this property.

For Example,
Moving n disks from A to C using B can be easily solved by Moving n-1 disks from A to B using C + Moving 1 disk from A to C + Moving n-1 disks from B to C using A.

Here you can see we are able to reduce the problem from n to n-1,then n-1 will be reduce to n-2 and so on till we reach a case that is trivial for us to answer i.e. n=0.
This trivial case is often called base case in recursion.
There are many applications of Recursion such as in Linked Lists,Trees,Graphs etc.

How to move n discs from Tower1 to Tower2 ?
1. Move n-1 discs from Tower1 to Tower 3
2. Move nth disc from Tower1 to Tower2
3. Move n-1 discs from Tower3 to Tower1

This is the recursion concept behind tower of hanoi.
In C, we may write (just printing the steps)

#include <stdio.h>
void towerofhanoi(int n,char src[],char dst[],char ext[]){
      towerofhanoi(n-1,src,ext,dst); \\moving n-1 discs from source to spare  
      towerofhanoi(n-1,ext,dst,src); \\moving n-1 discs back from spare to destination
void move(int n,char src[],char dst[]){
    static int count = 0;
    printf("%d: move %d from %s to %s\n",count,n,src,dst);
int main(){
  int discs;
  printf("\t\tTower of Hanoi\n\n");
  printf("Enter the number of Discs: ");
  return 0;
Post a Comment

Amazing Facts about Programming

Amazing Facts about programming  The first programmer was a lady named Ada Lovelac . She was a writer and gifted mathematician...

Popular Tutorials