Tower of Hanoi program in C || recursive function || C programming
In this, we are going to see a program that use both recursive and non-recursive functions to solve towers of Hanoi Problem with help of C Programming Language.



#include <stdio.h>
void T(int, char, char, char);
void main()
{
    int n;
    printf("Enter the number of disks: ");
    scanf("%d", &n);
    T(n, 'A', 'C', 'B');
}

void T(int n, char frompeg, char topeg, char auxpeg)
{
    //if there is only one disk, make the move and return
    if (n == 1)
    {
        printf("\n%s%c%s%c", "move disk 1 from peg ", frompeg, " to peg ", topeg);
        return;
    }

    //move top n-1 disks from A to B, using C as auxiliary
    T(n - 1, frompeg, auxpeg, topeg);

    //move remaining disk from A to C
    printf("\n%s%d%s%c%s%c", "move disk ", n, " from peg ", frompeg, " to peg ", topeg);

    //move n-1 disk from B to C using A as auxiliary
    T(n - 1, auxpeg, topeg, frompeg);
}


#ENJOY CODING


Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post