stackoverflow1453

Programming&&Games&&Life

Archive for Struggle

Write a recursive function which implements Towers of Hanoi puzzle

/*
	Name:
	Copyright: Deitel C How to Program
	Author: StackOverflow1453
	Date: 19.04.2013 20:07:52
	Description:
	
	Recursive algorith is as followS:

a) Move n – 1 disks from peg 1 to peg 2, using peg 3 as a temporary holding area.
b) Move the last disk (the largest) from peg 1 to peg 3.
c) Move the n – 1 disks from peg 2 to peg 3, using peg 1 as a temporary holding area.


*/

#include <stdio.h>
void instructions(int numberOfDisksToBeMoved, int initialTower, int finalTower, int temporaryHoldingTower);

int main(void) {

int n; /* number of disks */

printf( "Enter the starting number of disks: " );
scanf( "%d", &n );

instructions(n,1,3,2);

return 0;

}

void instructions(int numberOfDisksToBeMoved, int initialTower, int finalTower, int temporaryHoldingTower){
	
	if  (numberOfDisksToBeMoved==1){
	
		printf( "%d  --> %d\n",initialTower,finalTower );
		return;
		}
		//Move n – 1 disks from peg 1 to peg 2, using peg 3 as a temporary holding area.
		instructions(numberOfDisksToBeMoved-1, initialTower,  temporaryHoldingTower, finalTower);
		//Move the last disk (the largest) from peg 1 to peg 3.
		printf( "%d  --> %d\n",initialTower,finalTower );
		//Move the n – 1 disks from peg 2 to peg 3, using peg 1 as a temporary holding area.	
		instructions(numberOfDisksToBeMoved-1, temporaryHoldingTower, finalTower, initialTower);
	
}