C++: Must use a while loop. 1. Write a program that reads in a positive integer
ID: 3923455 • Letter: C
Question
C++: Must use a while loop. 1. Write a program that reads in a positive integer from the user and outputs the sum of its digits. Your program must verify the input is valid. For example, if the user inputs 37248, the sum of its digits is 8 + 4 + 2 + 7 + 3 = 24, and your output will therefore be 24. If the user inputs 45, the sum of its digits is 5 + 4 = 9, and your output will be 9. (Hint: There is a reason why the digits are added in the reverse order – think about the place value system – units, tens, … – modulo operator % and the integer division operator /).
2. Must use a do-while loop: Allow the user to repeat the calculations in Problem 2 as many times as they wish (for possibly different inputs).
Explanation / Answer
1.Using while loop:
#include <iostream>
using namespace std;
int main() {
int num;
cout<<"Enter the number : ";
cin>>num;
int sum=0;
while(num!=0)
{
sum+=num%10; //taking modulus resulting in unit digit
num/=10;
}
cout<<" Sum of digits : "<<sum;
return 0;
}
2.Do-while loop:
#include <iostream>
using namespace std;
int main() {
int num;
cout<<"Enter the number : ";
cin>>num;
int sum=0;
do
{
sum+=num%10;
num/=10;
}while(num!=0);
cout<<" Sum of digits : "<<sum;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.