Update Move Count (Counter) - Towers of Hanoi - C program
c, recursion
Solution
Return the value of the `count` from your function to the `main`. For this you have to call it from `main` as
int c = TOH(n,'A','C','B');
and change return type of your function to `int`.
int TOH(int,char,char,char);
I changed your function a little bit:
int TOH(int n,char x,char y,char z)
{
int count = 0;
if(n>0){
count = TOH(n-1, x, z, y);
printf("\nMove disk %d from peg %c to peg %c\n", n, x, y);
count++;
count += TOH(n-1, z, y, x) ;
}
return count;
}
Problem
I wrote this C program for moving a number of disks (n) from peg A to peg C while tracing the path. However, I do not know how/where to put a count call/ increment so that the total number of moves is kept track of and printed out at the end. Any advice would be appreciated. (Originally I had it printing in the TOH function, which did not work so I removed the printf(..) line) I changed the variables so it would increase readability; however, the count output is way off. For number of plates = 3, count = 239. For number of plates 4, count = 130,431 ``` #include <stdio.h> int TOH(int,char,char,char); int main() { int n; printf("\nEnter number of plates:"); scanf("%d",&n); int c = TOH(n,'A','C','B'); printf("\n"); printf("Total number of moves = %d \n ", c); return 0; } int TOH(int n,char first,char third,char second) { int count; if(n>0){ count=TOH(n-1, first, second, third); printf("Move disk %d from peg %c to peg %c\n", n, first, third); count++; count+= TOH(n-1, second, third, first); } return count; } ```