+ 1

how to print the sum of numbers present in an array

the array has a sequence of numbers they are {5,10,15,20,25,30,35,40,45,50} how to print their sum

3rd Dec 2016, 2:23 PM
Tindu
4 Antworten
+ 4
fastest way is var arr = [1,2,4,5,7]; var sum = arr.reduce(function(x,y){return x+y;},0); alert(sum); sum: 19
3rd Dec 2016, 2:34 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 3
use a for loop and for each iteration add a value to sum
3rd Dec 2016, 2:30 PM
Midhun Mathew
+ 1
If you want to write the code yourself, here's the loop block: for(int i=0;i<9;++i) { sum+=arr[i] ; } Just make it output the sum in the main block after this. You could make it more general by replacing the i<9 condition by i<length of array. ( OOPS, I'm sorry I just noticed that your question was for Java, the above code is for C/C++, so nevermind.)
3rd Dec 2016, 2:51 PM
Flynn Primepincer
Flynn Primepincer - avatar
0
public class Program { public static void main(String[] args) { int[] array = {5,10,15,20,25,30,35,40,45,50}; int sum = 0; for(int i : array){ sum += i; } System.out.println(sum); } }
14th Dec 2016, 2:01 AM
lowshuen