Spaces:
Running
Running
| Write the method | |
| int sum(int[] numbers) | |
| which calculates and returns the array's elements sum. | |
| Example method call: | |
| public static void main(String[] args){ | |
| int[] array = {1,2,3,4}; | |
| int sum = sum(array); | |
| System.out.println("Sum: " + sum); | |
| } | |
| Program outputs: | |
| Sum: 10 | |
| ============= | |
| import java.util.Random; | |
| import java.util.Arrays; | |
| public class Test { | |
| public static void main(String[] args) { | |
| final Random r = new Random(); | |
| for (int test = 1; test <= 3; test++) { | |
| System.out.println("Test " + test); | |
| int length = r.nextInt(5) + 5; | |
| int[] array = new int[length]; | |
| for (int i = 0; i < length; i++) { | |
| array[i] = r.nextInt(10) + 1; | |
| } | |
| System.out.println("Array: " + Arrays.toString(array)); | |
| System.out.println("Sum: " + sum(array)); | |
| System.out.println(""); | |
| } | |
| } | |
| public static int sum(int[] numbers){ | |
| int sum = 0; | |
| for (int num : numbers) { | |
| sum += num; | |
| } | |
| return sum; | |
| } | |
| } | |
| Test 1 | |
| Array: [6, 2, 3, 10, 3, 9, 5, 1] | |
| Sum: 39 | |
| Test 2 | |
| Array: [1, 6, 10, 8, 10, 8, 3, 1] | |
| Sum: 47 | |
| Test 3 | |
| Array: [9, 7, 6, 4, 6, 8] | |
| Sum: 40 | |