Java Program to find sum of array

Given an array of integers, find sum of its elements.

Examples :

Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6

Input : arr[] = {15, 12, 13, 10}
Output : 50

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Java Program to find sum of elements in a given array  */
class Test
{
     static int arr[] = {12,3,4,15};
       
     // method for sum of elements in an array 
     static int sum()
     {
         int sum = 0; // initialize sum
         int i;
        
         // Iterate through all elements and add them to sum
         for (i = 0; i < arr.length; i++)
            sum +=  arr[i];
        
         return sum;
     }
       
     // Driver method
     public static void main(String[] args) 
     {
         System.out.println("Sum of given array is " + sum());
        }
 }

chevron_right


Please refer complete article on Program to find sum of elements in a given array for more details!

My Personal Notes arrow_drop_up

Recommended Posts:

    Article Tags :

    1


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.