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.
-
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 sizesize
is created to store the elements. - The user is prompted to input the elements of the array, which are stored in
inputArray
.
- The user is prompted to input the size of the array (
-
Sum Calculation:
- A variable
sum
is initialized to0
. - A
for
loop iterates through the array, adding each element tosum
.
- A variable
-
Output:
- After the loop, the total sum is printed to the console using
System.out.println()
.
- After the loop, the total sum is printed to the console using
Key Points:
- Sum Logic:
- The program uses a simple
for
loop to traverse the array and accumulate the sum of its elements.
- The program uses a simple
- Type Handling:
- The program uses a
double
type forsum
to handle cases where the user modifies the program to deal with decimal values, even though the input is restricted to integers.
- The program uses a
- 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