How to add values inside an array?

0

I have an integer value and need to transform into an array to do the sum of each of the elements individually. I did this (example):

int n = 1230;
string sn = Convert.ToString(n); //converte em string
char[] narr = sn.ToArray(); //converte em array

int t = narr[0] + narr[1]; // realiza a soma e retorna t = 99 (49+50 equivalencia decimal 1 e 2 na tabela ASCII)

Console.WriteLine("\n narr[0] = {0}", narr[0]); // narr[0] = 1
Console.WriteLine("\n narr[1] = {0}", narr[1]); // narr[1] = 2

How to add the value of each index (t = 1 + 2)?

    
asked by anonymous 26.11.2018 / 04:12

1 answer

1

You will need to go through each element, transform into numeric, and add:

public static void Main()
{
    string input = "1230a";
    int t = 0;
    foreach (char c in input)
    {
        int x;
        if (int.TryParse(c.ToString(),out x))
        {
            t+= x;
        }
    }

    Console.WriteLine("\n t = {0}", t); // t = 6
}

I've put an example using an input string, not a number, so it can contain non-numeric characters to give a better example. Using your input, it would look like:

int n = 1230;
string input = n.ToString();

Update :

Understanding that Array is just a structure, the idea of adding each element inside implies running through them, but for the versions of the .NET Framework, you can use LINQ to do this:

using System.Linq;

/*...*/

int y= 0;
int t = input.Select(x=> (int.TryParse(x.ToString(), out y) ? y : 0)).Sum();
Console.WriteLine("\n t = {0}", t); // t = 6
    
26.11.2018 / 05:05