Towers of Hanoi Using Iteration

I am trying to write a towers of hanoi c++ program using iteration. i have written the same program using recursion but i am having trouble using iteration. so far this is what i have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;

int exp(int n){
    int two=1;
    for (int i=0; i<n; ++i){
        two *= 2;
    }
    two = two-1;
    return two;
}

int main()
{
    int disk;
    int start=1;
    int middle=2;
    int last=3;
    cout << "Please enter the number of disks: ";
    cin >> disk;
    cout << endl;

    if ( disk <= 0) cout << "You entered an invalid number." << endl;

    else if ( disk % 2 == 0 ){
        for ( int j=1; j<=exp(disk); j++){

            cout << "Move disk " << "1" << " from tower A to tower B." << endl;
            cout << "Move disk " << "2" << " from tower A to tower C." << endl;
            cout << "Move disk " << "3" << " from tower B to tower C." << endl;

        }
    }
    else if( disk % 2 == 1){
        for ( int j=1; j<=exp(disk); j++){

            cout << "Move disk " << "1" << " from tower A to tower C." << endl;
            cout << "Move disk " << "2" << " from tower A to tower B." << endl;
            cout << "Move disk " << "3" << " from tower C to tower B." << endl;

        }
    }

    return 0;
}


the program needs to allow the user to enter the number of disk they want to use then display instructions on how to complete the game.

i was thinking of using a nested loop but that was not working.
Topic archived. No new replies allowed.