Tower Of Hanoi using JAVA & C

Java code:
import java.util.Scanner;
public class Main {
 public static void main(String[]args) {
  int n, a = 1, b = 2, c = 3;
  Scanner input = new Scanner(System.in);
  System.out.println("Tower of Hanoi: ");
  System.out.print("Enter no. of Rings: ");
  n = input.nextInt();
  if(n<=0){
      System.out.println("Not Sufficient Rings:");
      System.exit(-1);
      }
  TOH directions = new TOH();
  directions.toh(n, a, b, c);
  input.close();
 }
}
class TOH {
 public void toh(int n, int a, int b, int c) {
  if (n > 0) {
   toh(n - 1, a, c, b);
   System.out.println("move a disc from " + a + " to " + c);
   toh(n - 1, b, a, c);
  }
 }
}

Output:
Run 1:
Run 2:



C code:
#include<stdio.h>
#include<stdlib.h>
//defining toh function.
void toh(int n,int a,int b,int c);
int main(){
    //variable n for user input & a,b,c are the towers.
    int n, a = 1, b = 2, c = 3;
    
    printf("Tower of Hanoi: \n");
    //taking no. of rings as input
    printf("enter no. of rings: ");
    scanf("%d", &n);
    
    //checking if user entered number below 1
    if(n<=0){
        printf("Not sufficient rings.\n");
        exit(-1);
    }
    //calling toh function
    toh(n,a,b,c);
    return 0;
}
void toh(int n,int a,int b,int c){
    if(n > 0){
        //using recursive method to give directions
        toh(n-1, a, c, b);
        printf("move a disc from %d to %d\n",a,c);
        toh(n-1,b,a,c);
    }
}


Output:
Run 1:

Run 2:

Comments

Popular posts from this blog

AI and Human Evolution

To Do List App (GUI) using C#

Snake Game using JAVA