Click here to Skip to main content
15,797,822 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
public static int sum(int[] array) {
    int total = 0;
    for (int i = 0; i < array.length; i++) {
        total = total + array[i];
    return total;

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!
Updated 17-Jan-23 11:01am

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.
Share this answer
What do I need to do to this code to get the sum of an array?
Call the function and pass it the array ...
int[] arr = {1,2,3,4,5,6};
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900