This is a Java Program to Accept Array Elements and Calculate Sum. An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. Aspecific element in an array is accessed by its index.
Enter the size of array and then enter all the elements of that array. Now we calculate the sum of elements of the array with the help of for loop.
Here is the source code of the Java Program to Accept Array Elements and Calculate Sum. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Array_Sum
{
public static void main(String[] args)
{
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:"+sum);
}
}
Output:
$ javac Array_Sum.java $ java Array_Sum Enter no. of elements you want in array:5 Enter all the elements: 1 2 3 4 5 Sum:15
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Java Books
- Buy Programming Books
- Practice Information Technology MCQs
- Apply for Information Technology Internship
- Practice Programming MCQs