HomeLanguagesJavaJava Program to Print Summation of Numbers

Java Program to Print Summation of Numbers

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
RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32548 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6922 POSTS0 COMMENTS
Nicole Veronica
12039 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12150 POSTS0 COMMENTS
Shaida Kate Naidoo
7060 POSTS0 COMMENTS
Ted Musemwa
7302 POSTS0 COMMENTS
Thapelo Manthata
7017 POSTS0 COMMENTS
Umr Jansen
7005 POSTS0 COMMENTS