We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
static int simpleArraySum(int n, int[] ar) {
int sum = 0;
for(int count = 0; count < ar.length; count++) {
sum = sum + ar[count];
}
return sum;
}
Steps:
1.) You declare a variable to hold the sum.
2.) Give that variable an initial value.
3.) Now do a for loop to pass through every single element in the array.
4.) The first statement in the for loop sets an initial value to its variable count (can be named anything), int count = 0. The second piece of code (count < ar.length) sets a condition for which the loop will continue to run through the array, in this case, it will run until the end of the array. The third piece of code (count++) will add one to the counter which is the code that makes the counter pass through the array by increments of one (step by step).
5.) The code inside the brackets {sum = sum + ar[count]} will take the initial value of sum and add all of the values found inside the array to it.
6.) Finally the return statement will simply print out the new values of sum given by the for loop.
*I hope this helps everyone, let me know if it does!
Simple Array Sum
You are viewing a single comment's thread. Return to all comments →
Here is a simple solution I came up with.