Tower of Hanoi program in C
In this post, you will learn the Tower of Hanoi program using the C programming language.
The Tower of Hanoi is a mathematical puzzle containing 3 pillars/towers with n disks each of a different size/diameter.
Given a stack of n disks arranged from biggest on the bottom to smallest on top put on a rod, along with two empty rods, the tower of Hanoi puzzle asks for the minimum number of moves required to move the stack from one rod to another, where moves are allowed only if they place smaller disks on the top of bigger disks.
Rules of Tower of Hanoi Problem
The rules for this puzzle are -
- We can move only one disk at a time.
- We can remove only the top disk.
- We can only place a disk above a disk of a bigger size.
C Program for Tower of Hanoi Problem Using Recursion
Recursion function is a function which is called by itself. In the given C program, we call a recursion function towerOfHanoi() to get the Tower of Hanoi. Here, we have three towers named A, B, and C and asked the user to provide the number of plates and stored it in a variable n. Then, we used the recursion function solve it.
#include <stdio.h>
void towerOfHanoi(int,char,char,char);
void main()
{
int n;
printf("How many plates?");
scanf("%d",&n);
towerOfHanoi(n,'A','B','C');
}
void towerOfHanoi(int n,char x,char y,char z)
{
if(n>0)
{
towerOfHanoi(n-1,x,z,y);
printf("\n%c -> %c",x,y);
towerOfHanoi(n-1,z,y,x);
}
}
Output of the above code
How many plates?3
A -> B
A -> C
B -> C
A -> B
C -> A
C -> B
A -> B
Related Articles
Prime factors of a number in cArmstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to reverse a number
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative