Write a static method to calculate the sum of a one dimensional array in Java
one dimensional array : {1,2,3,4,5,6}
Array always start from o index so 1 is array[0] and similary go on, In order to calculate sum of one dimensional array we need to use loop; so here we used for loop;
Program in details:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package assignments;
/**
*
* @author achyut1324
*/
public class Qs6array {
static int[] array = {7, 15, 2, 3};
public static void main(String[] args) {
System.out.println("sum : "+ sum(array));
}
public static int sum(int[] x){
int sum = 0;
for(int i=0; i<array.length;i++){
sum = sum + x[i];
}
return sum;
}
}
Output of the Program :
sum : 27
BUILD SUCCESSFUL (total time: 0 seconds)