This is another homework problem. I thought it was easier, and I wouldn't need help, but I keep getting a segmentation fault when running the program.
The assignment is to use a recursive function to output the amount of candybars we can buy with a user-inputted amount of money. Each candybar costs $1, and each candybar gives a coupon. 7 coupons can be redeemed for an additional candybar. The example he gave us is:
"For example, if we have $20 dollars then we can initially buy 20 candy bars. This gives us 20 coupons. We can redeem 14 coupons for 2 additional candy bars. These two additional
candy bars have 2 more coupons, so we now have a total of 8 coupons when added to the 6
left over from the original purchase. This gives us enough to redeem for 1 more candy bar.
As a result we now have 23 candy bars and 2 left over coupons."
Here is the code I have. When I don't get a segmentation fault, I get it returning zero.
//File Name: assg3.cpp
#include <iostream>
using namespace std;
int candybars=0;
int recursivecandy(int A, int B) //A is money, B is coupons
{
do
{
candybars = candybars + A +(B/7);
B = A + B/7, B%7;
A = 0;
return recursivecandy(A, B);
}while (B>=7);
}
int main()
{
int money;
int coupons=0;
cout << "Please enter the number of dollars you have: $";
cin >> money;
cout << "With " << money << " dollars, you can buy " << recursivecandy(money, coupons) << " candy bars.\n";
return 0;
}
Fairly straightforward, I use a do-while loop to run inside the recursive function because I want it run at least once (you start with no coupons, which is my stopping case). Does anyone see anything wrong? Any help would be greatly appreciated.