In this tutorial, you are going to learn to write a java program to find the sum of all array elements. We will see various approaches to perform the summation of array elements.
Example :
For input array arr=[2,4,1,3,6]
the output will be: 16
as 2+4+1+3+6 = 16
Program 1: Sum of an array using for loop in Java
- In the below program, we have used very simple approach to find the sum of array elements.
- First, we are taking the array size and array elements from the users.
- And using for loop we are iterating each element and performing addition on it.
- We have a sum variable to store the result of sum operation on each iteration.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
System.out.println("Enter the size of the array : ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int arr[] = new int [size];
int sum = 0;
System.out.println("Enter the array elements one by one ");
for(int i=0; i<size; i++){
arr[i] = s.nextInt();
sum=sum+arr[i];
}
System.out.println("Sum of array elements: "+sum);
}
}
Output
Program 2 : Find Array Sum using Recursion in Java
- In the below program, we are using the recursion concept to find the sum of the array.
- To perform recursion we have a method name sum with parameters sum(int[] arr, int n), that are calling itself again and again.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static int sum(int[] arr, int n)
{
if (n <= 0) {
return 0;
}
return sum(arr, n - 1) + arr[n - 1];
}
public static void main(String args[]){
System.out.println("Enter the size of the array : ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int arr[] = new int [size];
System.out.println("Enter the array elements one by one ");
for(int i=0; i<size; i++){
arr[i] = s.nextInt();
}
int sumResult = sum(arr, arr.length);
System.out.println("Array Elements are: "+Arrays.toString(arr));
System.out.println("Sum of array elements: "+sumResult);
}
}
Output