Code
Code

Reputation: 23

Trying to figure out how Summations

The question states that the method (public static int Sum (int[] input) should take an array of ints, and perform the following mathematics over the input data, X.

enter image description here

Here is my code I need to know if I'm doing this question correct.

package mathsassessment;

public class Sum {

    public static void main (String[] args){
        int[] arr1 = {1, 2, 3, 4, 5,};
        int sum = 0;
        for (int i = 0; i < arr1.length; i++) {
            sum += arr1 [i];
        }
        System.out.println("Sum is : " + sum);
    }
}

Upvotes: 1

Views: 48

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201437

It looks reasonable, except you didn't put it in a method named Sum. Also, in Java 8+, you could sum things with a stream like

public static int Sum(int[] input) {
    return Arrays.stream(input).sum();
}

Upvotes: 1

Related Questions