Java Program to Find Sum of Array Elements

Java Program to Find Sum of Array Elements

Java Program to Find Sum of Array Elements

import java.util.Scanner;

class ExArrayElementSum {
  public static void main(String args[]) {
    // create object of scanner.
    Scanner s = new Scanner(System.in);

    int n, sum = 0;

    // enter number of elements you want.
    System.out.print("Enter the elements you want : ");

    // read entered element and store it in "n".
    n = s.nextInt();
    int a[] = new int[n];

    // enter elements in array.
    System.out.println("Enter the elements:");

    // traverse the array elements one-by-one.
    for (int i = 0; i < n; i++) {
      a[i] = s.nextInt();
    }
    for (int num: a) {
      sum = sum + num;
    }
    // print the sum of all array elements.
    System.out.println("Sum of array elements is :" + sum);
  }
}
First run:
Enter the elements you want : 3
Enter the elements:
55
21
14
Sum of array elements is :90

Second run:
Enter the elements you want : 5
Enter the elements:
12
45
36
25
88
Sum of array elements is :206

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment