Towers of Hanoi - C Program

Program:
#include<stdio.h>
//#include<conio.h>
void hanoi(int,int,int,int);
void main()
{
    int no_of_disks, firstpeg=1,secondpeg=2,thirdpeg=3;//clrscr();;
    printf("Enter the no. of disks:");
    scanf("%d",&no_of_disks);
    printf("\n\n Tower of Hanoi problem with %d disks. \n\n", no_of_disks);
    hanoi(no_of_disks,firstpeg,secondpeg,thirdpeg);
    printf("\nSolved...\n");//getch();
}

void hanoi(int n,int peg1,int peg2,int peg3)
{
    if(n!=0)
    {
    hanoi(n-1,peg1,peg3,peg2);
    printf("move disk %d from peg%d to peg%d \n",n,peg1,peg3);
    hanoi(n-1,peg2,peg1,peg3);
    }
}

Output:
nn@linuxmint ~ $ gcc c21.c
nn@linuxmint ~ $ ./a.out
Enter the no. of disks:3


 Tower of Hanoi problem with 3 disks. 

move disk 1 from peg1 to peg3 
move disk 2 from peg1 to peg2 
move disk 1 from peg3 to peg2 
move disk 3 from peg1 to peg3 
move disk 1 from peg2 to peg1 
move disk 2 from peg2 to peg3 
move disk 1 from peg1 to peg3 

Solved...
nn@linuxmint ~ $

1 comment:

  1. it was very helpful to me....
    thank you for posting this. i have also made a c++ program with same concept but it's somewhat different in the recursive definition
    have a look at my code on my blog codingloverlavi.blogspot.com
    :):)

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...