Taking a number from a value

Hi, I live in Turkey and trying to learn how to program. Sorry for grammar mistakes from the begining. I have a book, and I read first chapter. It has a test at the end and I couldn't do the following question:

"Write a program that must be like this:

Write a number: 456
The sum of the numbers is: 15"

I couldn't find anything on the internet. Maybe because of the bad English :)

You could use a function:
1
2
3
4
5
6
7
8
9
10
int sumDigits(int number)
{
    int sum = 0;
    while (number)
    {
        sum += number %10;
        number /= 10;
    }
    return sum;
}

or
1
2
3
4
5
int sumDigits(int number, int init = 0)
{
    if (number == 0) return 0;
    return sumDigits( number / 10 , init + number % 10 );
}
Last edited on
closed account (Dy7SLyTq)
read it into a string and then parse the string and using atoi add each with a total variable
Topic archived. No new replies allowed.