Home >Backend Development >C++ >Tower of Hanoi program written in C language
The Tower of Hanoi is a mathematical puzzle. It consists of three rods and several discs of different sizes that slide onto any of the rods. The puzzle begins with disks stacked neatly on a rod in ascending order of size, with the smallest disk on top. We have to move the same stack to the third rod.
The goal of the puzzle is to move the entire stack to another rod, following these simple rules −
Only one disk can be moved at a time.
Each move involves taking the upper disc from one pile and placing it on top of another pile, that is, it can only be moved when it is on top of one pile disc.
Cannot place a disk on top of a smaller disk.
Input − 3
Output − A to B
A to C
− uses recursive function & solves the tower of Hanoi.
Example
#include<stdio.h> void TOH(int n,char x,char y,char z) { if(n>0) { TOH(n-1,x,z,y); printf("</p><p>%c to %c",x,y); TOH(n-1,z,y,x); } } int main() { int n=3; TOH(n,'A','B','C'); }Output
A to B A to C B to C A to B C to A C to B A to B
The above is the detailed content of Tower of Hanoi program written in C language. For more information, please follow other related articles on the PHP Chinese website!