JAVA Program for calculating the sum of all the elements of an array

Calculate the Sum of all the elements of an array

In this section, we learn about how we add all the elements of the array. The addition of all the elements of the array is quite easy.

This program is very simple, here we just apply a for loop from zero to size of the array.
In every iteration of the array, we just need to add the present index element with the sum variable and at the last, we will get the sum of whole elements. So now we discuss the working and implementation of the program in java language.

Algorithm for calculating the sum of all the elements of an array

  • Step 1. Initialize an array.
  • Step 2. Declare the scanner class for taking input.
  • Step 3. take array size from the user.
  • Step 4. Take element of array from the user.
  • Step 5. Print sum from calling sum function.

sum(int a[],int size)

  • Step 1. Initialize sum variable with zero.
  • Step 2. Initialize the loop from 0 to size of the array.
  • Step 3. add all the element of array with sum and again store it in the sum variable
  • Step 4. Return sum.

JAVA Code for calculating the sum of all the elements

import java.util.Scanner;
public class Main
{
     public static int sum(int[] arr,int size)
     {
         int sum=0;
         for(int i=0;i<size;i++)
         {
             sum=sum+arr[i];
         }
        return sum;
     }
     public static void main(String[] args) 
     {
         int[] a = new int[50];
         Scanner sc=new Scanner(System.in);
         System.out.print("enter size ");
         int size=sc.nextInt();
         System.out.println("enter Element");
         for(int i=0;i<size;i++)
             a[i]=sc.nextInt();
        System.out.println("sum: "+sum(a,size));
      }
}