Java Program to Find Sum of Array Elements
Last Updated :
26 Jan, 2023
Given an array of integers. Write a Java Program to find the sum of the elements of the array.
Examples:
Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6
Input : arr[] = {15, 12, 13, 10}
Output : 50
15 + 12 + 13 + 10 = 50
An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be quickly sorted or searched. All the items of the array are stored at contiguous memory locations.
Array Elements: Each item of an array is an Element. All the elements in an array must be of the same type.
Algorithm
- Initialize an array arr and a variable sum.
- Set the value of sum=0.
- Start a for loop from index 0 to the length of the array – 1.
- In every iteration, perform sum = sum + arr[i].
- After the termination of the loop, print the value of the sum.
Java
class Test {
static int arr[] = { 12 , 3 , 4 , 15 };
static int sum()
{
int sum = 0 ;
int i;
for (i = 0 ; i < arr.length; i++)
sum += arr[i];
return sum;
}
public static void main(String[] args)
{
System.out.println( "Sum of given array is "
+ sum());
}
}
|
Output
Sum of given array is 34
Time Complexity: O(n)
Auxiliary Space: O(1)
One Line Solution
- One Line solution using Java inbuilt method
- import java.util.Arrays is an important statement
Syntax
Arrays.stream(arrayName).sum();
Java
import java.util.Arrays;
import java.io.*;
class GFG {
public static void main (String[] args) {
int [] nums = { 1 , 2 , 3 , 4 , 5 };
int sum = Arrays.stream(nums).sum();
System.out.println(sum);
}
}
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Using Recursion:
Java
import java.io.*;
class GFG {
public static int sumArray( int [] arr, int n) {
if (n == 0 ) {
return arr[n];
}
return arr[n] + sumArray(arr, n- 1 );
}
public static void main(String[] args) {
int [] arr = { 1 , 2 , 3 , 4 , 5 };
int n = arr.length;
int sum = sumArray(arr, n- 1 );
System.out.println( "Sum of the elements in the array: " + sum);
}
}
|
Output
Sum of the elements in the array: 15
Time Complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...