From 56fbc342957fc15046e944b3269874c878a40b84 Mon Sep 17 00:00:00 2001 From: Jayneel Shah <80264736+jayneel-shah18@users.noreply.github.com> Date: Thu, 21 Oct 2021 20:38:42 +0530 Subject: [PATCH] Create towerOfHanoi.c The code contains recursive solution to Tower of Hanoi problem. It is a popular application of recursion. --- C/towerOfHanoi.c | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C/towerOfHanoi.c diff --git a/C/towerOfHanoi.c b/C/towerOfHanoi.c new file mode 100644 index 00000000..d6016852 --- /dev/null +++ b/C/towerOfHanoi.c @@ -0,0 +1,36 @@ +/* +Name - Jayneel Shah +Date - 21/10/21 +Topic - Application of Recursion +Program to implement Tower Of Hanoi*/ + +#include + +void towerOfHanoi(int n, int start, int end) +{ + if (n == 1) + { + printf("Move disk from %d to %d.\n", start, end); + } + else + { + int other = 6 - (start + end); + //this will move n-1 disks from top of largest disk to the middle disk by the help of recursion + towerOfHanoi(n - 1, start, other); + printf("Move disk from %d to %d.\n", start, end); + //this will move those n-1 disks from middle to the last tower after shifting the largest disk to the last tower + towerOfHanoi(n - 1, other, end); + } +} + +int main() +{ + int n, towers; + printf("Enter the number of discs: "); + scanf("%d", &n); + printf("Enter the number of towers: "); + scanf("%d", &towers); + towerOfHanoi(n, 1, towers); + + return 0; +}