A recursive solution to the towers of Hanoi problem in C

#include <stdio.h>
 
 void Hanoi(int, char, char, char)
 
 int main()
 {
    char src,aux,dest;
    int n;
 
    src='A';
    aux='B';
    dest='C';
 
    printf("Enter the number of discs in the game : ");
    scanf("%d",&n);
    if(n == 0)
        printf("nNothing has to be moved.n");
    else
        Hanoi(n,src,aux,dest);
    return 0;
 }
 void Hanoi(int n,char src,char aux,char dest)
 {
    if(n == 1)
        printf("Move disc from peg %c to peg %c.n",src,dest);
    else{
        Hanoi(n-1,src,dest,aux);
        Hanoi(1,src,aux,dest);
        Hanoi(n-1,aux,src,dest);
    }
 }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.