0

I have converted string to char[], but now when I try to get a total of all the numbers in the array, I get a wrong output. The goal is that if the user enters a number as a string e.g - 12, the output should be 3 i.e 1 + 2, another example - 123 should be 1+2+3 = 6.

I am new to coding. My apologies for any inconvienence.

static void Main(string[] args)
{
    int sum = 0;
    String num = Console.ReadLine();
    char[] sep = num.ToCharArray();
    for (int i = 0; i < sep.Length; i++)
    {
        sum += (sep[i]);
    }
    Console.WriteLine(sum);
    Console.ReadLine();
}
preciousbetine
  • 2,959
  • 3
  • 13
  • 29
Van Bever
  • 19
  • 5
  • 1
    Please show what input you are giving it, and what output you are seeing. Also: What output did you expect to see instead, and why? – 15ee8f99-57ff-4f92-890c-b56153 Oct 22 '19 at 18:24
  • 1
    Hello and welcome to StackOverflow. Can you please update your post to include what output you are getting and what the *expected* should be? From first look, what if you type in per say, `1010981`, how are you going to differentiate what is `10` or `1` or `81`? – Trevor Oct 22 '19 at 18:24
  • if you input 12 it should give 1+2 =3 – Van Bever Oct 22 '19 at 18:26
  • you are adding a "char" data type value with an "integer" data type value here : `sum += (sep[i])`...this will surely give you an error..can you try this: `sum += i` – Bishal Sarker Oct 22 '19 at 18:34
  • sum += i Doesn't works – Van Bever Oct 22 '19 at 18:35
  • @BishalSarker Adding a char to an integer will surely work. OP's code compiles and runs. I have tested it. Chars are integers. – 15ee8f99-57ff-4f92-890c-b56153 Oct 22 '19 at 18:43
  • @VanBever You haven't said what your goal is. What is the desired sum of the string "cat"? 312? Or some other number? Is "cat" valid input at all? – 15ee8f99-57ff-4f92-890c-b56153 Oct 22 '19 at 18:45
  • 2
    @EdPlunkett the Goal is that if user enters a number as a string for e.g 12 the out put should 3 i.e 1+2, another example 123 ->1+2+3 = 6. I am new to coding my apologies for any inconvienence. – Van Bever Oct 22 '19 at 18:55
  • @VanBever Thank you for the clarification! Can you edit your question and add that, so nobody will be confused? – 15ee8f99-57ff-4f92-890c-b56153 Oct 22 '19 at 19:05
  • @EdPlunkett Done! any soultion or explanation regarding the problem? – Van Bever Oct 22 '19 at 19:24
  • @VanBever Ljubomir Bacovic's answer is correct. preciousbetine's is correct as well, and uses the safer TryParse() (try typing "cat" into Ljubomir's version and see what happens). I would try both, understand both, and see if you have a preference. John Wu's is correct, but if you can't easily figure out what it's doing, leave that stuff for another day. He won't mind. – 15ee8f99-57ff-4f92-890c-b56153 Oct 22 '19 at 19:29
  • The value of a character like `'1'` is 49. This because `'1'` is encoded in [ASCII](https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html). – John Alexiou Oct 22 '19 at 20:06

3 Answers3

2

If you want to calculate sum of digits, you need to convert each char to int first. Char needs to be converted to string and then parsed into int. Your original code contains implicit conversion, which converts 1 and 2 into 49 and 50 (ASCII), thus the sum ends up being 99.

Try this code instead:

static void Main(string[] args)
{
    int sum = 0;
    String num = Console.ReadLine();
    char[] sep = num.ToCharArray();
    for (int i = 0; i < sep.Length; i++)
    {
        sum += int.Parse(sep[i].ToString());
    }
    Console.WriteLine(sum);
    Console.ReadLine();
}
2

You are currently adding ascii values. The ascii value of 1 is 49 and that of 2 Is 50... You need to use int.TryParse to convert from char to int.

int value;
for (int i = 0; i < sep.Length; i++)
{
    if (int.TryParse (sep[i].ToString(),out value))
        sum += value;
}
preciousbetine
  • 2,959
  • 3
  • 13
  • 29
1

Just for fun here is a LINQ solution.

var sum = num.Select( c => int.Parse((string)c) ).Sum();

This solution takes advantage of the fact that a string is also an IEnumerable<char> and therefore can be treated as a list of characters.

The Select statement iterates over the characters and converts each one to an integer by supplying a lambda expression (that's the => stuff) that maps each character onto its integer equivalent. The symbol is typically prounced "goes to". You might pronounce the whole expression "C goes to whatever integer can be parsed from it."

Then we call Sum() to convert the resulting list of integers into a numeric sum.

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • Thanks, I am not an advance Coder, Cany ou please tell me what is happening in you c=> thing? – Van Bever Oct 22 '19 at 18:44
  • 1
    @VanBever [See here =>](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator) and it's called a lambda operator and `c => int.Parse((string)c)` is the expression body. – Trevor Oct 22 '19 at 18:45