SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Flow Of Control
Exercise:
Programming Projects
Question:3 | ISBN:9780132846813 | Edition: 5

Question

Suppose you can buy a chocolate bar from the vending machine for $1 each. Inside every chocolate bar is a coupon. You can redeem seven coupons for one chocolate bar from the machine. You would like to know how many chocolate bars you can eat, including those redeemed via coupon, if you have n dollars.

For example, if you have 20 dollars then you can initially buy 20 chocolate bars. This gives you 20 coupons. You can redeem 14 coupons for two additional chocolate bars. These two additional chocolate bars give you two more coupons, so you now have a total of eight coupons. This gives you enough to redeem for one final chocolate bar. As a result you now have 23 chocolate bars and two leftover coupons.

Write a program that inputs the number of dollars and outputs how many chocolate bars you can collect after spending all your money and redeeming as many coupons as possible. Also output the number of leftover coupons. The easiest way to solve this problem is to use a loop.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

#include <iostream> 
using namespace std; 
 
int main() 
{ 
int amountBars, amountCoupons; 
cout << endl << "Enter the number of dollars you have to spend: "; 
cin >> amountBars; 
amountCoupons = amountBars; 
while (amountCoupons >= 7) { 
  amountBars += amountCoupons / 7; 
  amountCoupons = amountCoupons / 7 + amountCoupons % 7; 
  } 
cout << "You can buy " << amountBars << " bars"; 
cout << " and will have " << amountCoupons << " unused coupon(s)." << endl; 
  
return 0; 
} 

 

0 0

Discussions

Post the discussion to improve the above solution.