# Coding Sample Questions | Part 7 | Codewindow.in

Problem Statement :

We are given n disks and a series of rods, we need to transfer all the disks to the final rod under the given constraints−
✓ We can move only one disk at a time.
✓ Only the uppermost disk from the rod can be moved.
✓ Any bigger disk cannot be placed on the smaller disk

Input Format:
Input number of disks

Output Format:
Show the complete action of disks moving from one rod to other rod to reach destination.

Constraints:
0<N<=14

Sample Input 1 :
3
Sample Output 1 :
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

Solution:

C

```//https://codewindow.in

#include <stdio.h>
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c",from_rod, to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);

printf("\n Move disk %d from rod %c to rod %c", n,from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);

}

int main()
{
int n = 4;
towerOfHanoi(n, 'A', 'C', 'B');
return 0;
}

//end
```

JAVA

```//https://codewindow.in

class GFG
{
static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}

public static void main(String args[])
{
int n = 4;
towerOfHanoi(n, 'A', 'C', 'B');
}
}

//end
```

Python

```#https://codewindow.in

def TowerOfHanoi(n , from_rod, to_rod, aux_rod):
if n == 1:
print("Move disk 1 from rod",from_rod,"to_rod",to_rod)
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk",n,"from rod",from_rod,"to_rod",to_rod)
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)

n = 4
TowerOfHanoi(n, 'A', 'C', 'B')

#end
```