15,797,822 members
See more:
```public static int sum(int[] array) {
int total = 0;
for (int i = 0; i < array.length; i++) {
total = total + array[i];
}
}
```

What I have tried:

I'm sure I sound stupid, I'm super new to coding and I just need to see how this work. Any help is greatly appreciated!
Posted
Updated 17-Jan-23 11:01am

## Solution 1

In the function, It takes in an integer array as a parameter and calculates the sum of all the elements in the array.
The function first declares a variable total and initializes it to 0. It then uses a for loop to iterate through each element of the array, starting from index 0 and ending at the last index. Inside the for loop, it adds the value of the current array element to the total variable. After the for loop completes, the function returns the total value.

The function uses the length property of the array array.length to get the number of elements in the array and uses the for loop to iterate through all the elements.

## Solution 2

Quote:
What do I need to do to this code to get the sum of an array?
Call the function and pass it the array ...
Java
```int[] arr = {1,2,3,4,5,6};
System.out.println(sum(arr));
```

v2