Java program to find sum of array elements

In this java program, we are going to learn how to read an array and find sum of all array elements?
Submitted by IncludeHelp, on October 29, 2017

Read 'N' array elements, and find sum of all elements using java program.

This program is an example of one dimensional array in java. Here, we are reading N array elements and printing sum of all given array elements.

Program to find sum of all elements in java

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

Output

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

Java Array Programs »



Related Programs

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.