Reputation: 21
I want to convert int array to int so i can add them.
Example
int[] x = {1, 2, 3};
sum=x[0] + x[1] + x[2];
I have a loop for getting an input from user but i have to add all the values of every inputted.
Upvotes: 1
Views: 885
Reputation: 233
You can do this in a number of ways.
first by making a loop yourself.
static int Sum(int[] array)
{
int sum = 0;
foreach (var item in array)
{
sum += item;
}
return sum;
}
static void Main()
{
int[] x = new int[] { 1, 2, 3 };
Console.Write(Sum(x).ToString());
}
second, using the Sum() method in the System.Linq
library
using System.Linq;
////
int[] x = new int[] { 1, 2, 3 };
Console.Write(x.Sum());
thank you USEFUL
for feedback if it worked for you
Upvotes: 3
Reputation: 9650
It is not really clear what the problem is. Your code seems fully functional, so it is difficult to know what you are really trying to achieve and what the underlying issue it.
But certainly a simple loop would work fine.
int sum = 0;
for(int loop=0; loop < x.Length; loop++)
{
sum += x[loop];
}
You can also do this via Linq (I see somebody else posted that example, so I won't repeat it).
Upvotes: 1
Reputation: 11151
Use the .Sum
LINQ method:
var x = new int[] { 1, 2, 3 };
var sum = x.Sum(); // gives 6
Upvotes: 3