Hello,
I currently have a problem that I am working on that entails a recursive coin counter that does not include global variables or loops. I have gotten most of it down, however it seems that I need to add a single coin that is being counted, plus the result from the coins(sum-10), and I am failing to understand how to do that, as I have attempted to put a counter in for returning it.. Any help would be appreciated, and I apologize if it is a simple fix.
#include <iostream>
#include <vector>
using namespace std;
int coins(int sum)
{
int count = 0;
if (sum < 0)
return 0;
if (sum == 0)
return 0;
if (sum >= 25)
{
return sum + coins(sum - 25);
return count++;
}
else if (sum >= 10)
{
return sum + coins(sum - 10);
return count++;
}
else if (sum >= 5)
{
return sum +coins(sum - 5);
return count++;
}
else if (sum >= 1)
{
return sum +coins(sum - 1);
return count++;
}
}
/***************************************
* main()
***************************************/
void main()
{
int cents, n;
// Get user input
cout << "Enter an amount in cents: ";
cin >> cents;
First, posting code with code tags makes it easier to read and refer to.
You have:
1 2 3 4 5
if (sum >= 25)
{
return sum + coins(sum - 25);
return count++;
}
Your compiler should tell you that line 4 will never be used. You return from line 3, so the the above is effectively same as:
1 2 3 4
if (sum >= 25)
{
return sum + coins(sum - 25);
}
Lets say that sum is 50 initially. You call coins(50), which returns: 50 + coins(25)
We know that coins(25) returns 25 + coins(0)
and that coins(0) returns 0.
Therefore, coins(50) returns 50 + 25 + 0. Is it really true that answer to 50 is 75?
How much is sum % 25?
How much is sum % 25?
Lets take 63. 63 / 25 = 2 and 63 % 25 = 13. 13 / 10 = 1 and 13 % 10 = 3. 3 / 5 = 0 and 3 % 5 = 3. 3 = 3.
Two 25c coins, one 10c coin, no 5c coins, and three 1c coins. 2+1+0+3=6 coins.