Array: Find the sum of all elements in an array

Q) Find the sum of all elements in an array

Example:

Array: 27 26 11 41 53 18 90 82 79 46

Output:
Sum= 473

public class ArraySumSample {
  
  public int sumArray (int [] sampleArray){
    int sum=0; //inititalizing the sum to zero
    for(int i=0; i<sampleArray.length; i++){ //running a loop through the length of the array
      sum+= sampleArray[i]; //add all the elements of the array
    }
    return sum; //return the sum of all elements of the array
  }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: