0
        int Number = 12;
        int Sum = 0;
        string sNumber = Convert.ToString(Number);
        for(int i = 0; i < sNumber.Length; i++)
        {
            Sum = Sum + Convert.ToInt32(sNumber[i]);
        }
        Console.WriteLine(Sum);

it should show 3, But instead its showing 99. What is actual mistake.

Shad0W
  • 19
  • 1

6 Answers6

2

If you iterate the characters in a string, you'll get chars. The problem is that converting a char to an int with Convert.ToInt32(), will result in the ASCII Unicode UTF-16 value of that char.

The ASCII Unicode UTF-16 value of '1' = 49 and for '2' is 50 which sums 99.

You should make it a string first.

int Number = 12;
int Sum = 0;
string sNumber = Convert.ToString(Number);
for(int i = 0; i < sNumber.Length; i++)
{
    Sum = Sum + Convert.ToInt32(sNumber[i].ToString());
}
Console.WriteLine(Sum);
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
1

The problem is that Convert.ToInt32(sNumber[i]) is getting the numeric value of the character at position i, i.e. Convert.ToInt32('1') gives 49. Note that this value is a char and therefore Convert.ToInt32('1') returns the value of the UTF-16 character.

Why convert it to a string when plain mathematics will do what you want.

int number = 12;
int sum = 0;

while (number > 0){
    sum += number % 10;
    number /= 10; // Integer division
}

Console.WriteLine(sum);
phuzi
  • 12,078
  • 3
  • 26
  • 50
0

Change it to the following:

        int Number = 12;
        int Sum = 0;
        string sNumber = Convert.ToString(Number);
        for (int i = 0; i < sNumber.Length; i++)
        {
            Sum = Sum + Convert.ToInt32(sNumber.Substring(i,1));

        }
        Console.WriteLine(Sum);

Use Substring instead of [] Convert.ToInt32(char x) will give you the UTF16 value of the char. See: https://learn.microsoft.com/de-de/dotnet/api/system.convert.toint32?view=net-5.0#System_Convert_ToInt32_System_Char_

Connor Low
  • 5,900
  • 3
  • 31
  • 52
kosist
  • 2,868
  • 2
  • 17
  • 30
0

Convert.ToNumber(char) returns code of character in ASCII. In your example 1 have code 49 and 2 have code 50. 49 + 50 results in 99

You need to use Sum = Sum + int.Parse(sNumber[i].ToString()) to get actual value of digit

JL0PD
  • 3,698
  • 2
  • 15
  • 23
0

no need to convert to string for this. Use simple mathematics.

int Number = 123;
            int Sum = 0;

            while (Number != 0)
            {
                Sum += (Number % 10);
                Number = Number / 10;
            }
            System.Console.WriteLine(Sum);
Amit Verma
  • 2,450
  • 2
  • 8
  • 21
0

Since it hasn't been posted, here's a simple one-liner using Linq:

int Sum = Number.ToString().Sum(x => (int)char.GetNumericValue(x));
oRoiDev
  • 339
  • 1
  • 8