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

Tower of Hanoi program written in C language

PHPz
Release: 2023-09-13 10:13:06
forward
1547 people have browsed it

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;);
}
Copy after login

Output

A to B
A to C
B to C
A to B
C to A
C to B
A to B
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template