public class ArrayMethod
2: import java.util.Scanner;
4: /**
5: * A program with methods that take arrays.
6: *
7: * @author Mark Young (A00000000)
8: */
9: public class ArrayMethod {
11: // the size of the array
12: public static final int MAX = 5;
14: public static void main(String[] args) {
15: // create the variables
16: Scanner kbd = new Scanner(System.in);
17: int[] number = new int[MAX];
19: // read the values
20: System.out.println("\nEnter " + MAX + " numbers below:");
21: for (int i = 0; i < MAX; i++) {
22: number[i] = kbd.nextInt();
23: }
24: kbd.nextLine();
26: // pass the array to a method (which returns an int value)
27: int sum = sumArray(number);
29: // report the result of the previous method
30: System.out.println("\nThe sum of those numbers is " + sum + ".\n");
32: // report the result of another method that takes an array
33: System.out.println("\nThe sum of the first three numbers is "
34: + sumPartOfArray(number, 3) + ".\n");
35: }
37: /**
38: * Find the sum of all the elements of an array.
39: *
40: * @param arr the array whose elements are to be summed
41: * @return the sum of all elements in arr
42: */
43: public static int sumArray(int[] arr) {
44: int sum = 0;
45: for (int i = 0; i < arr.length; i++) {
46: sum += arr[i];
47: }
48: return sum;
49: }
51: /**
52: * Find the sum of SOME elements of an array.
53: *
54: * @param arr the array whose elements are to be summed
55: * @param count how many elements from the array are to be summed
56: * @return the sum of the first count elements of arr
57: */
58: public static int sumPartOfArray(int[] arr, int count) {
59: int sum = 0;
60: for (int i = 0; i < count; i++) {
61: sum += arr[i];
62: }
63: return sum;
64: }
66: }