Java Program to find out the sum of all elements in an array

Here we are explaining how to write a java program to find out the sum of the array elements. It's a simple program. Here first we read the limit of the array and read the array elements. Then we will find out the sum of the elements and display it.

How to read an integer number in java?

In java, we can read an integer number by using nextInt() the function. an example is shown below.


System.out.println("Enter the limit of the array:")
n=scanner.nextInt();
 

here scanner is the object of the Scanner class in java.

How to implement the java program to find out the sum of the array elements?

First, we have to declare the class ArraySum.Then open the main function. Create an object of the scanner class. Read the limit of the array into the variable n. Then read the numbers into the array array[] using for loop. Then used by another for loop to find out the sum of the array elements as sum=sum+num. After that, display the sum.

ALGORITHM

STEP 1: Declare the class ArraySum with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Read the limit of the numbers from the user into the variable n.

STEP 4: Read the elements of the array using for loop.

STEP 5: By using another for loop calculate sum=sum+num.

STEP 6: Display the sum of the array elements as the sum 

 

Java Source Code

                                          import java.util.Scanner;
public class ArraySum {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        int[] array = new int[50];
        int sum = 0, n;
        System.out.println("Enter the limit of the array:");
        n = scanner.nextInt();
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            array[i] = scanner.nextInt();
        }
        scanner.close();
        for (int num: array) {
            sum = sum + num;
        }
        System.out.println("Sum of the elements in the array:" + sum);
    }
}
                                      

OUTPUT

Enter the limit of the array:3
Enter the elements of the array:
1
2
3
Sum of the elements in the array:6