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
Regarding Local Variable Passing in Thread
Datetime.Tryparse Century Control C#
Async Network Operations Never Finish
Accessing Properties Through Generic Type Parameter
How to Share Data Between Forms
Datatrigger Does Not Change Text Property
Add Shape Information to a Listview When Its Created
Metadata Were Not Loaded Using Metadatatype
When Should I Use Gc.Suppressfinalize()
Is Bcrypt a Good Hashing Algorithm to Use in C#? How to Find It
Why Is Typedreference Behind the Scenes? It's So Fast and Safe... Almost Magical!
How to Get the Line Number Which Threw Exception
Why Are Subjects Not Recommended in .Net Reactive Extensions
Performing Inserts and Updates with Dapper
Can You Configure Log4Net in Code Instead of Using a Config File
Display a Image in a Console Application