Home >Backend Development >C++ >Tower of Hanoi program written in C language

Tower of Hanoi program written in C language

PHPz
PHPzforward
2023-09-13 10:13:061548browse

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.

Example

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,&#39;A&#39;,&#39;B&#39;,&#39;C&#39;);
}

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete