void towers(int N, int presentPeg, int toPeg, int tempPeg) { if(N > 0) { towers(N-1, presentPeg, toPeg, tempPeg); cout << "Move disc from Peg#" << presentPeg << " to Peg#" << toPeg << endl; towers(N-1, tempPeg, presentPeg, toPeg); } }
The out for 3 discs is:
Move disc from Peg#1 to Peg#3 Move disc from Peg#1 to Peg#3 Move disc from Peg#2 to Peg#1 Move disc from Peg#1 to Peg#3 Move disc from Peg#2 to Peg#1 Move disc from Peg#2 to Peg#1 Move disc from Peg#3 to Peg#2
Which is obviously wrong. I'm calling the function like so: "towers(n, 1, 3, 2);" where n=3. Can anyone spot a problem?