+ 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
4 Respuestas
+ 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
+ 3
use a for loop and for each iteration add a value to sum
+ 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.)
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);
}
}