Sum of digits entered.

A problem that lets the user enter any positive integer, but you do not have to check for this, and then calculates the sum of the digits and displays this to user. For example, if user enters 14503, the outputted sum of the digits would be 13. You need turn in an algorithm, C++ source code and output.

how do i even go about making 1 add to 4? and so on. I'm lost.
Read the input as a string.

Iterate over each character of the string.

Use the appropriate standard library function to convert the character to an int.

Add the int to the running total.
im not sure about strings.

should it go something like this?

14503 % 10 ---> 3

14503 / 10 ---> 1450

1450 % 10 ---> 0

1450 / 10 ----> 145
That will do too.

You just need an accumulator variable to store sum of your digits and wrap yor digits extraction into loop. You just did the most crucial thing yourself.
Is this right?

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

unsigned getUnsigned(const string&);
unsigned sumDigits(unsigned);

int main(int argc, char *argv[]) {
int n;

while (true) {
n = getUnsigned("Enter a positive integer: ");
cout << "sum of digits = " << sumDigits(n) << endl << endl;
}
return 0;
}

unsigned sumDigits(unsigned n) {
if (n < 10) return n;
return (n % 10) + sumDigits(n / 10);
}

unsigned getUnsigned(const string &prompt) {
stringstream ss;
string line;
bool inputOk = false;
int n;

cout << prompt;
do {
getline(cin,line);
ss.clear(); ss.str(line);

if (!(ss >> n) || (n < 1) || ss.good()) {
cout << "invalid input, try again" << endl << prompt;
} else {
inputOk = true;
}
} while (inputOk == false);
return n;
}
Nope, it won't work for numbers > 99.

Your algorithm should be something like:
1) create accumulator variable and initialize it to 0
2) get last digit using (% 10) operation and add it to accumulator
3) Discard last digit from number using (/ 10) operation
4) if number isn't equals to 0 repeat from step 2
5) return accumulator
Topic archived. No new replies allowed.