1) Write a C++ program to compute the sum of the digits of a positive number. Pr
ID: 672927 • Letter: 1
Question
1) Write a C++ program to compute the sum of the digits of a positive number. Prompt the user to enter the number. If the user enters a 0 or a negative number, you program should prompt the user to re-enter the number, i.e. you should only read positive numbers greater than 0. Once the number is entered your program should print the sum of its digits. For example, if the user enters 245, the your program should print, Sum of Digits = 11. Finally, the program should be interactive, i.e. Ask the user if he/she wants to run the program again or quit.
**Hint: To determine the digits for 245, the algorithm is as follows**
245 % 10 = 5
24 % 10 = 4
2 % 10 = 2
2) Suppose we can buy a chocolate bar from the vending machine for $1 each. Inside every chocolate bar is a coupon. We can redeem 7 coupons for one chocolate bar from the machine. We would like to know how many chocolate bars can be eaten, including those redeemed via coupon, if we have n dollars.
For example, if we have 20 dollars then we can initially buy 20 chocolate bars. This gives us 20 coupons. We can redeem 14 coupons for 2 additional chocolate bars. These two additional chocolate bars have 2 more coupons, so we now have a total of 8 coupons when added to the six leftover from the original purchase. This gives us enough to redeem for one final chocolate bar. As a result we now have 23 chocolate bars and 2 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. Your program should also be interactive, i.e. Ask the user if he/she wants to run the program again or quit.
**The easiest way to solve this problem is to use a control structure, such as a while loops.**
Explanation / Answer
1.
#include<iostream.h>
#include<conio.h>
void main()
{
char ans='y';
int i,n,sum=0,b;
while(ans=='y')
{
sum=0;
while(n<=0)
{
cout<<"enter no";
cin>>n;
}
for(i=0;i<3;i++)
{
b=n%10;
sum=sum+b;
n=n/10;
}
cout<<"Sum is "<<sum;
cout<<"Do you want to continue[y/n]";
ans=getch();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.