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);
    }
}

This Java program calculates the sum of array elements using a separate method.

  1. Method findSum(int array[]):

    • This method accepts an integer array as a parameter.
    • It calculates the sum of the array elements using a for loop.
    • The calculated sum is printed using System.out.println().
  2. Main Method:

    • An instance of the AddElementsInArray class is created.
    • The user is prompted to enter the size of the array (size) using a Scanner object.
    • An integer array inputArray[] of size size is created.
    • The user is prompted to input the elements of the array, which are stored in inputArray.
  3. Method Call:

    • The findSum() method is called, passing inputArray as an argument to compute and display the sum of the array elements.
    • The findSum() method demonstrates passing arrays as parameters in Java.
    • The findSum() method can be reused for any integer array without modifying the main logic.
    • The logic for summing the array elements is moved to the findSum() method, making the program modular and reusable.

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