How To Sum Up An Array In Java
To create a method that sum’s up an array, first of all you have to know how to create a method, if you know how to create a method then let dive right in, else I suggest u look up my article on Java methodlink
Below are the steps to create a method that sum’s up an array
Steps
1.create a method name with an argument of an array e.g
public static int sumMyArray(int[] array){}
2.Inside your method initialize variable depending on your array type or method return type ( it advisable to use your method return type), make it equals to 0 e.g
public static int sumMyArray(int[] array){
int sum = 0;
}
3.Loop through your array and add each value in ur array to sum e.g
public static int sumMyArray(int[] array){
int sum = 0;
for(int i=0; i < array.length; i++)
sum += array[i];
return sum;
}
Lets test our our method
test Example
public class Sample {
public static void main(String[] args){
int[] num = {1, 3, 5, 7, 10, 11, 15, 2, 1};
int sum = sumMyArray(num);
System.out.println(sum);
}
public static int sumMyArray(int[] array){
int sum = 0;
for(int i=0; i < array.length; i++)
sum += array[i];
return sum;
}
}
//output:55