Java Program to find sum of array elements

Program

import java.util.Scanner;
public class SumOfArrayElements {
  public static void main(String[] args) {
    System.out.println("Enter the required size of the array: ");
    Scanner reader = new Scanner(System.in);
    int size = reader.nextInt();
    Integer inputArray[] = new Integer[size];
    System.out.println("Enter the elements of the array: ");
    for (int i = 0; i < size; i++) {
      inputArray[i] = reader.nextInt();
    }
    double sum = 0;
    double average = 0;
    for (int i = 0; i < size; i++) {
      sum = sum + inputArray[i];
    }
    System.out.println("Sum of given numbers is: " + sum);
  }
}

This Java program calculates the sum of all elements in an array.

  1. Input from User:

    • The user is prompted to input the size of the array (size).
    • A Scanner object (reader) is used to take input.
    • An array inputArray[] of size size is created to store the elements.
    • The user is prompted to input the elements of the array, which are stored in inputArray.
  2. Sum Calculation:

    • A variable sum is initialized to 0.
    • A for loop iterates through the array, adding each element to sum.
  3. Output:

    • After the loop, the total sum is printed to the console using System.out.println().

Key Points:

  • Sum Logic:
    • The program uses a simple for loop to traverse the array and accumulate the sum of its elements.
  • Type Handling:
    • The program uses a double type for sum to handle cases where the user modifies the program to deal with decimal values, even though the input is restricted to integers.
  • Scalability:
    • Works for any size of the array as specified by the user.

Output

javac .\SumOfArrayElements.java
java SumOfArrayElements
Enter the required size of the array: 
5
Enter the elements of the array: 
10
20
30
40
50
Sum of given numbers is: 150.0