How to add values within an array?

Asked

Viewed 2,214 times

0

I have an integer value and need to transform it into an array to sum each of the elements individually. I did it as follows (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 sum the value of each index (t = 1+2)?

1 answer

2


You will need to scroll through each element, turn into numerical, 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 put an example using an input string and not a number, so it can contain non-numeric characters to better illustrate. Using your entrance, you’d be:

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 >= 3.5 of . net Framework, you can use LINQ for 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
  • 1

    Running I can perform the sum, used decision structure I can perform the sum of part or total of the int, but adding value of integers converted into array (using array) is not possible?

  • @Asalbu updated the response

Browser other questions tagged

You are not signed in. Login or sign up in order to post.