Open In App

Java Program to Print Summation of Numbers

Last Updated : 21 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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

  1. Create a variable named sum and initialize it to 0.
  2. Traverse the array through a loop and add the value of each element into sum.
  3. 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));
    }
}


Output

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


Output

The sum of elements of given array is: 13


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads