Problem Solving using C Language

0 of 77 lessons complete (0%)

Functions

Tower of Hanoi

Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  • No disk may be placed on top of a smaller disk.
Problem Statement of Tower of Hanoi

Program for Tower of Hanoi

#include <stdio.h>  
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)  
{      
	if (n==1)      
	{          
		printf("\nMove disk 1 from rod : %d",from_rod);        
		printf("\nMove disk 1 to rod : %d",to_rod);        
		return;      
	}      
	towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);      
	printf("\nMove disk %d from rod : %d",n,from_rod);    
	printf("\nMove disk %d to rod : %d",n,to_rod);      
	towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);  
}  
int main()  
{      
	int n = 3; // Number of disks      
	towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods      
	return 0;  
} 

Desired Input/output
Input : 2

Output : Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C

Input : 3
Output : Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C