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
- 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
class GFG {
static int sumOfArray( int arr[])
{
int sum = 0 ;
for ( int i = 0 ; i < arr.length; i++) {
sum = sum + arr[i];
}
return sum;
}
public static void main(String[] args)
{
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
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args)
{
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
Share your thoughts in the comments
Please Login to comment...