Click here to Skip to main content
15,913,055 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi there,

I have an array in this format int[] i = {0,1,2,3,4,5,6,7,8,9};

Please help me with a procedure thatI can use to get the sum of the values in my array.

Eg.
int value=(0+1+2+3+4+5+6+7+8+9);
int sum= value;


Thanks in advance

Martin
Posted
Updated 17-Jul-11 3:05am
v2
Comments
Dalek Dave 17-Jul-11 9:05am    
Edited for CodeBlock and Readability.

there are many ways, you can do like this.

int sum = i.Sum();
 
Share this answer
 
v2
Comments
thatraja 17-Jul-11 8:38am    
5!
Salmen Essridi 17-Jul-11 8:48am    
Thank you.
Dalek Dave 17-Jul-11 9:04am    
Simplest method!
Espen Harlinn 17-Jul-11 10:16am    
Nice and simple, my 5
Sergey Alexandrovich Kryukov 18-Jul-11 3:52am    
As easy as that, a 5.
--SA
Try below code.

int[] i = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = i.Sum();
 
Share this answer
 
Comments
thatraja 17-Jul-11 8:38am    
5!
RaisKazi 17-Jul-11 9:05am    
Thanks Man !!!
The usual thing to do is to create an int to hold the total value and set it to 0.
The you do a for loop across each value in the array adding it to the total. Once the loop is done you have your total.
 
Share this answer
 
Comments
thatraja 17-Jul-11 8:37am    
Classic way, 5!
You can use LINQ to do this.
See an example here[^].
 
Share this answer
 
Comments
thatraja 17-Jul-11 8:37am    
5!
Abhinav S 17-Jul-11 8:46am    
Thank you.
Another way,

C#
int[] intArray = { 1, 2, 3, 4, 5, 6 };
int result = 0;
Array.ForEach(intArray, item => result += item);


Hope it helps.
 
Share this answer
 
Comments
Abhinav S 18-Jul-11 4:10am    
This is also another approach. Univote corrected.
Mohammad A Rahman 18-Jul-11 4:15am    
I Appreciate, Abhinav :) I just tried to show a way.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900