tower of hanoi location code example

Example 1: tower of hanoi

//code by Soumyadeep Ghosh
//insta : @soumyadepp
//linked in: https://www.linkedin.com/in/soumyadeep-ghosh-90a1951b6/
#include <bits/stdc++.h>

using namespace std;

void toh(int n,char a,char b, char c)
{
  if(n>0)
    {
        /*move n-1 disks from a to b using c*/
        toh(n-1,a,c,b);
        /*move a disc from a to c using b and display this step performed. Also note that a and c are different in the next called function*/
        cout<<"Move a disk from "<<a<<" to "<<c<<endl;
        toh(n-1,b,a,c);
    }
}
int main()
{
  int n;
  cin>>n;
  //names of the disks are a,b,c
  toh(n,'a','b','c');
  return 0;
}
//thank you!

Example 2: tower of hanoi

/// find total number of steps 
int towerOfHanoi(int n) {
  /// pow(2,n)-1
  if (n == 0) return 0;
  
  return towerOfHanoi(n - 1) + 1 + towerOfHanoi(n - 1);
}

Tags:

Cpp Example