Given an array of integers, print the sum of all the elements in an array.
Examples:
Input: arr[] = {1,2,3,4,5}
Output: 15
Input: arr[] = {2, 9, -10, -1, 5, -12}
Output: -7
Approach 1: Iteration in an Array
- Create a variable named sum and initialize it to 0.
- Traverse the array through a loop and add the value of each element into sum.
- Print sum as the answer.
Below is the implementation of the above approach.
Java
// Java Program to print the sum // of all the elements in an array class GFG {       static int sumOfArray( int arr[])     {         // initialise sum to 0         int sum = 0 ;                 // iterate through the array using loop         for ( int i = 0 ; i < arr.length; i++) {             sum = sum + arr[i];         }           // return sum as the answer         return sum;     }       // Driver code     public static void main(String[] args)     {         // print the sum         int arr[] = { 1 , 2 , 3 , 4 , - 2 , 5 };         System.out.println(             "The sum of elements of given array is: "             + sumOfArray(arr));     } } |
The sum of elements of given array is: 13
Time Complexity: O(N), where N is the size of array
Approach 2: IntStream.of(arrayName).sum()
Inbuilt function IntStream.of(arrayName).sum() is used to sum all the elements in an integer array.
Syntax:
IntStream.of(arrayName).sum();
Below is the implementation of the above approach.
Java
// Java Program to print the sum // of all the elements in an array   // import IntStream import java.util.stream.IntStream;   class GFG {       // Driver code     public static void main(String[] args)     {         // print the sum         int arr[] = { 1 , 2 , 3 , 4 , - 2 , 5 };         System.out.println(             "The sum of elements of given array is: "             + IntStream.of(arr).sum());     } } |
The sum of elements of given array is: 13