Sum of each digit

Hello
Last edited on
Where are you taking the sum of the digits?

Line 9: You're testing the number(count), not the sum of the digits.
BTW, why is this a while loop? There is no reason for a loop here. Use an if statement.


Could you help me with the code please ?
Break the problem down into smaller pieces and solve those. Then the complete program is just a matter of putting together the pieces you have made.

Start with finding the sum of the digits of a single integer. I'd make this into a separate function - it makes it easy then to incorporate it into a larger program.

Not sure how to do that? Then start by isolating/extracting a single digit from the integer. Use %10 to get the right-most decimal digit. How would you get the next digit? Divide the original number by 10 and then use %10 again. Repeat until the number is zero.
I am still having trouble with the printing of sum of all digit
Specifically, what sort of trouble are you having? If you show the updated version of your code then things might become clearer and someone may be able to help further.
Chervil already gave you the formula for calculating the sum of the digits.

start by isolating/extracting a single digit from the integer. Use %10 to get the right-most decimal digit. How would you get the next digit? Divide the original number by 10 and then use %10 again. Repeat until the number is zero.

1
2
3
4
5
6
7
8
9
10
11
int sum_of_digits (int num)
{   int sum = 0;
    int dig;
    
    while (num)             //  Repeat until 0
    {   dig = num % 10;     //  Get least significant digit
        sum += dig;         //  Add to sum
        num /= 10;          //  Divide by 10 to drop least significant digit
    }
    return sum;
}

Last edited on
Still can't figure it out . Can someone write it for me please
Sorry, we're not going to write it for you. I've already given you a function to calculate the sum of the digits of a number. All you have to do is call that function to get the sum of the digits, then determine if the sum is divisible by 7. What is so hard?

As Chervil previously asked, post your current code and we'll be happy to point out any problems.


[Code]
#include <iostream>
f 7
Last edited on
Always avoid global variables unless absolutely necessary. I'm not even sure why you have n and sum global, as the parameters in the scope sumDigits() mask them. In other words, your parameters in sumDigits() are not the global variables n and sum.


Thanks for your help all, I can't figure out how to print n from 0-1000 (sum of each digit in the number) to show it is a multiple of 7

Use the same logic as you did for your original post.
Topic archived. No new replies allowed.