Related Articles

Related Articles

Java Program to Print Summation of Numbers
  • Last Updated : 21 Oct, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output

The sum of elements of given array is: 13

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :