Java Program to find sum of array elements using methods
Program
import java.util.Scanner;
public class AddElementsInArray {
public void findSum(int array[])
{
int sum = 0;
for(int i=0; i<array.length; i++){
sum = sum + array[i];
}
System.out.println("Sum of the elements of the array ::"+sum);
}
public static void main(String[] args)
{
AddElementsInArray addElementsInArray = new AddElementsInArray();
System.out.println("Enter the required size of the array: ");
Scanner reader = new Scanner(System.in);
int size = reader.nextInt();
int inputArray[] = new int [size];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<size; i++){
inputArray[i] = reader.nextInt();
}
addElementsInArray.findSum(inputArray);
}
}
Output
javac AddElementsInArray.java
java AddElementsInArray
Enter the required size of the array:
5
Enter the elements of the array:
10
20
30
40
50
Sum of the elements of the array ::150