Spaces:
Running
Running
Create 9b. Sum of array elements
Browse files
Week 3: Objects, files and exceptions/9b. Sum of array elements
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Write the method
|
| 2 |
+
|
| 3 |
+
int sum(int[] numbers)
|
| 4 |
+
|
| 5 |
+
which calculates and returns the array's elements sum.
|
| 6 |
+
|
| 7 |
+
Example method call:
|
| 8 |
+
public static void main(String[] args){
|
| 9 |
+
int[] array = {1,2,3,4};
|
| 10 |
+
|
| 11 |
+
int sum = sum(array);
|
| 12 |
+
System.out.println("Sum: " + sum);
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
Program outputs:
|
| 16 |
+
Sum: 10
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
=============
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
import java.util.Random;
|
| 26 |
+
import java.util.Arrays;
|
| 27 |
+
|
| 28 |
+
public class Test {
|
| 29 |
+
public static void main(String[] args) {
|
| 30 |
+
final Random r = new Random();
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
for (int test = 1; test <= 3; test++) {
|
| 34 |
+
System.out.println("Test " + test);
|
| 35 |
+
|
| 36 |
+
int length = r.nextInt(5) + 5;
|
| 37 |
+
int[] array = new int[length];
|
| 38 |
+
for (int i = 0; i < length; i++) {
|
| 39 |
+
array[i] = r.nextInt(10) + 1;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
System.out.println("Array: " + Arrays.toString(array));
|
| 43 |
+
System.out.println("Sum: " + sum(array));
|
| 44 |
+
System.out.println("");
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
public static int sum(int[] numbers){
|
| 52 |
+
int sum = 0;
|
| 53 |
+
for (int num : numbers) {
|
| 54 |
+
sum += num;
|
| 55 |
+
}
|
| 56 |
+
return sum;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
Test 1
|
| 65 |
+
Array: [6, 2, 3, 10, 3, 9, 5, 1]
|
| 66 |
+
Sum: 39
|
| 67 |
+
|
| 68 |
+
Test 2
|
| 69 |
+
Array: [1, 6, 10, 8, 10, 8, 3, 1]
|
| 70 |
+
Sum: 47
|
| 71 |
+
|
| 72 |
+
Test 3
|
| 73 |
+
Array: [9, 7, 6, 4, 6, 8]
|
| 74 |
+
Sum: 40
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
|