-2

I am trying to write a code that sums the digits of a number and it should work, but I can't find where I am doing it wrong, I have a working code in Python for this and I tried to do it the same way in C# but.. Here are the two codes

Python:

number = "12346546"
summ=0
for i in number:
    summ+=int(i)
print summ

C#:

string num = "2342";
int sum = 0;

for (int i = 0; i < num.Length; i++)
{
    int number = Convert.ToInt32(num[i]);
    sum += number;
}
Console.WriteLine(sum);

Edit: I used the Debugger and I found that when I am converting the numbers they turn out to be completely different numbers, but if I convert the whole string then it is converting correctly... how to fix this?

Habib
  • 219,104
  • 29
  • 407
  • 436
Darkbound
  • 3,026
  • 7
  • 34
  • 72
  • Typo in your for loop: try "i < num.Length" or "i <= num.Length-1" – Steve Czetty May 14 '14 at 17:17
  • 4
    -1 -- You didn't even describe your problem. If you get an error *paste* it into the question. If you get an unexpected output *paste* the output you get *and* write the expected output. – Bakuriu May 14 '14 at 17:19
  • Bakuriu thanks about pointing that out but I actually did at the end of my post the "Edit:", but obviously it was not really necessary since in a few seconds several users told me where my mistake is before I managed to Edit my post. – Darkbound May 14 '14 at 17:25

7 Answers7

4

num[i] is a char and Convert.ToInt32 will return the ASCII code of the char instead of the actual numerical value.Use:

int number = Convert.ToInt32(num[i].ToString());

Also change i < num.Length-1 to i < num.Length

Edit: To make it more clear here is an example:

int n1 = Convert.ToInt32('0'); // Uses Convert.ToInt32(char) result -> 48
int n2 = (int) '0'; // cast from char to int result -> 48
int n3 = Convert.ToInt32("0"); // Uses Convert.ToInt32(string) result -> 0
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • Yes, thanks I noticed that as soon as I used your converting method, it's working now! :) Thanks about the ASCII explanation, I was expecting that the reason was something similar. – Darkbound May 14 '14 at 17:20
  • Just a clarifying question: num[i].ToString() takes the ith element and converts it to a String on its own making it totally independent from the original string and that's why now its converting correctly? – Darkbound May 14 '14 at 17:27
  • @Darkbound yes, when you convert it to string, you are using [this](http://msdn.microsoft.com/en-us/library/sf1aw27b(v=vs.110).aspx) overload of Convert.ToInt32 and that's why it gives the expected result – Selman Genç May 14 '14 at 17:52
3

replace Convert.ToInt32(num[i])

by

Convert.ToInt32(num[i].ToString())

else, you will get an ascii value... (cause num[i] is a char)

see msdn

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
2

There is no null at the end of a C# string, so you don't have to worry about it, and thus do not require the "-1" in your loop. However, there is a much easier way:

string num = "2342";
int sum = num.ToCharArray().Select(i => int.Parse(i.ToString())).Sum();

This converts the string to a character array, converts them all to ints (returning an IEnumerable<int> in the process) and then returns the sum of them all.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • There *is no* null at the end in a C# string. – Tim S. May 14 '14 at 17:20
  • @TimS. clarified. Thanks for the feedback! – BradleyDotNET May 14 '14 at 17:22
  • This will not compile, `int.Parse` expects a `string` type parameter, and you are trying to pass a character. Also, there is no need to do `ToCharArray`, you can apply the LINQ on string as well. – Habib May 14 '14 at 17:27
  • @Habib, yep, forgot the .ToString on the char. I wasn't aware of the "Sum" function on String, which would be a shorter (though perhaps less clear to those unaware of the function) way of doing the same thing. – BradleyDotNET May 14 '14 at 17:30
  • @BradleyDotNET, string implements `IEnumerable`, so you will get LINQ with it. – Habib May 14 '14 at 17:31
  • 1
    @Habib, Learn something new every day... Thanks for the information – BradleyDotNET May 14 '14 at 17:31
1

Convert.ToInt32(num[i]); would give you the ASCII value for the character digit. For example for character 1 you will get 49.

Use char.GetNumericValue like:

for (int i = 0; i < num.Length; i++)
{
    int number = (int) char.GetNumericValue((num[i]));
    sum += number;
}

You also need to modify your loop to continue till Length, since you are using <.

If you want to use LINQ then you can do:

int sum = num.Select(r => (int)char.GetNumericValue(r)).Sum();
Habib
  • 219,104
  • 29
  • 407
  • 436
1

A one line solution using Linq:

string num = "2342";
int sum = num.Sum(c=> Convert.ToInt32(c.ToString()));

Here's a fiddle: https://dotnetfiddle.net/3jt7G6

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
0

You can combine a few things.

You can select a collection of chars from a string using Linq (Sum() is a Linq method).

You still need to convert those characters into numbers; you can do this by converting a character to a string and parsing that or you can use another built-in method.

var sum = num.Sum(i => Char.GetNumericValue(i));
48klocs
  • 6,073
  • 3
  • 27
  • 34
0

char is, at its core, just a number. It just happens to be a number representing a character.

Here are some solutions that highlight this:

int sum = num.Sum(c => c) - '0' * num.Length;

// or

int sum = 0;    
for (int i = 0; i < num.Length; i++)
{
    sum += num[i] - '0';
}
Tim S.
  • 55,448
  • 7
  • 96
  • 122