Sum of Digits in C#

Sum of digits in C#

You could do it arithmetically, without using a string:

sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}

Display the sum of digits in a number entered by the user

This is a very common mistake. char is really just a number - the encoding value of the character represented by the char. When you do Convert.ToInt32 on it, it sees the char as a number and says "alright let's just convert this number to 32 bits and return!" instead of trying to parse the character.

"Wait, where have I used a char in my code?" you might ask. Well, here:

Convert.ToInt32(num[count]) // 'num[count]' evaluates to 'char'

To fix this, you need to convert the char to a string:

nums[count] = Convert.ToInt32(num[count].ToString());
^^^^^^^^^^^^^^^^^^^^^

Now you are calling a different overload of the ToInt32 method, which actually tries to parse the string.

How to sum individual digits of integer?

int i = 723;
int acc;
do {
acc = 0;
while (i > 0)
{
acc += i % 10;
i /= 10;
}
i = acc;
} while(acc>=10);

% 10 gives the final digit each time, so we add that into an accumulator. /= 10 performs integer division, essentially removing the final digit each time. Then we repeat until we have a small enough number.



Related Topics



Leave a reply



Submit