C Programming code for Tower Of Hanoi Algorithm DSA

Write a Modular C Programming code for Tower Of Hanoi Algorithm DSA

faq.disk3

Tower of Hanoi is a mathematical puzzle where we have three rods (AB, and C) and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest disk is placed on the top and they are on rod A. The objective of the puzzle is to move the entire stack to another rod (here considered C), obeying the following simple rules: 

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  • No disk may be placed on top of a smaller disk.

Refer : C Programming HackerRank all solutions for Loops | Arrays | strings | Data Structures | Linked lists | Stacks | Queues | Binary Trees

 

CODE:

#include<stdio.h>
int z=1;
void towers(int n,char source,char dest,char aux)
{
 if(n==1)
 {
     printf("Step %d: Move disk 1 from %c to %c\n",z++,source,dest);
 }
 else{
    towers(n-1,source,aux,dest);
    printf("Step %d: Move disk %d from %c to %c\n",z++,n,source,dest);
    towers(n-1,aux,dest,source);
 }
}
int main()
{
    int n;
    char A,B,C;
    printf("Enter no of disks: ");
    scanf("%d",&n);
    printf("sequence:\n");
    towers(n,'A','C','B');
}

OUTPUT

Enter no of disks: 4
sequence:
Step 1: Move disk 1 from A to B
Step 2: Move disk 2 from A to C
Step 3: Move disk 1 from B to C
Step 4: Move disk 3 from A to B
Step 5: Move disk 1 from C to A
Step 6: Move disk 2 from C to B
Step 7: Move disk 1 from A to B
Step 8: Move disk 4 from A to C
Step 9: Move disk 1 from B to C
Step 10: Move disk 2 from B to A
Step 11: Move disk 1 from C to A
Step 12: Move disk 3 from B to C
Step 13: Move disk 1 from A to B
Step 14: Move disk 2 from A to C
Step 15: Move disk 1 from B to C

Process returned 0 (0x0)   execution time : 1.761 s
Press any key to continue.

Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, Stacks, Queues, Binary Trees, MISC, Solved model question papers & Hacker Rank all solutions on the below page:

Top 100+ C Programming codes – KLE Technological University







Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

Welcome to FactsPrime

Sorry, We have detected that you have activated Ad-Blocker. Please Consider supporting us by disabling your Ad Blocker, It helps us in maintaining this website. To View the content, Please disable adblocker and refresh the page.

Thank You !!!