tower.c

/*
 * tower of Hanoi program
 * user enters number of disks to be moved
 * program loops until EOF
 *
 * Matt Bishop, ECS 36A, Fall 2019
 */
#include <stdio.h>
#include <string.h>

/*
 * macros
 */
#define MAXINPUT	100	/* maximum length of input */

/*
 * the recursive tower of Hanoi solution
 * move ndisks from fromtower to totower
 * temptower is a tower used to hold disks temporarily
 *
 * returns the number of moves made
 */
int tower(int ndisks, char fromtower, char totower, char temptower)
{
	int n;		/* nu,ber of disks moved */

	/* base case: move 1 disk */
	if (ndisks == 1){
		printf("Move top disk from tower %c to tower %c\n",
						fromtower, totower);
		return(1);
	}
	/* now recurse -- move n-1 disks to the temptower 1 to the */
	/* totower, then n-1 from the temptower to the totower     */
	n = tower(ndisks-1, fromtower, temptower, totower);
	n += tower(1, fromtower, totower, temptower);
	n += tower(ndisks-1,  temptower, totower, fromtower);

	/* return the number of disks moved */
	return(n);
}

/*
 * the main routine
 */
int main(void)
{
	int n;			/* number of disks to move */
	int nmoves;		/* number of moves */
	char buf[MAXINPUT];	/* input buffer */

	/* prompt for the number of disks */
	printf("Number of disks on A (EOF to exit): ");

	/*
	 * now loop until the user wants to bail
	 */
	while(fgets(buf, MAXINPUT, stdin) != NULL){
		/* check for the string "EOF\n" (smartypants!) */
		if (strcmp(buf, "EOF\n") == 0)
			return(0);
		/* convert this to an integer, reporting an error if needed */
		if (sscanf(buf, "%d", &n) != 1 || n <= 0){
			fprintf(stderr, "Enter a positive integer\n");
		}
		else{
			/* move those disks */
			nmoves = tower(n, 'A', 'C', 'B');
			/* announce the results -- note proper grammar */
			printf("*** Moving %d disks from A to C takes %d ",
								    n, nmoves);
			if (nmoves == 1)	printf("move\n");
			else			printf("moves\n");
		}
		/* prompt for the number of disks */
		printf("Number of disks on A (EOF to exit): ");
	}

	/* EOF doesn't terminate line, so do that and exit */
	putchar('\n');
	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: [email protected]
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh