The answer I have in Recursion is not the same as the one in the book
Aug 15, 2017 at 7:39am UTC
Write your question here.
I am dealing with recursion. On exercise 12 of Walter Savitch textbook the answer is 6 but I get 36 on the mystery(3). Please help
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Put the code you need help with here.
#include<iostream>
using namespace std;
int mystery(int n);
//Precondition: n >= 1.
int main() {
cout << "mystery 2" << mystery(2) << endl;
cout << "mystery 3" << mystery(3) << endl;
cout << "mystery 4" << mystery(4) << endl;
cout << "mystery 5" << mystery(5) << endl;
return 0;
}
int mystery(int n)
{
if (n <= 1)
return 1;
else
return (mystery(n - 1) + n);
}
Here is the snap shot of the program running:
mystery 23
mystery 36
mystery 410
mystery 515
--------------------------------
Process exited after 0.03284 seconds with return value 0
Press any key to continue . . .
Aug 15, 2017 at 7:49am UTC
OKAY!! Okay Okay I have found the problem Walter Savitch is 100% correct. The problem is on my output statement.
Thank you all.
Aug 15, 2017 at 7:52am UTC
Here is my resolved answer snap shot:
mystery 2 = 3
mystery 3 = 6
mystery 4 = 10
mystery 5 = 15
--------------------------------
Process exited after 0.02245 seconds with return value 0
Press any key to continue . . .
Topic archived. No new replies allowed.