/* This program demonstrates basic methods on arrays. 1. printing an array 2. computing the sum of all elements in an array 3. sequential search an array for a target Laura Toma csci 107 */ public class ArrayBasicFun { static ReadStream r; public static void main (String args[]) { r = new ReadStream(); int i, n; int[] a; //declare a variable a that stores an array System.out.print("Enter array size: "); n = r.readInt(); r.readLine(); //create an array of this size a = new int[n]; //read the array from user i = 0; while (i < a.length) { System.out.print("Enter element " + i + ": "); a[i] = r.readInt(); r.readLine(); i++; } //print the array to the user printArray(a); //compute the sum of all elements in the array int s; s = sumArray(a); System.out.print("The sum of all element in the array is: " + s); //ask for a target int t; System.out.print("Enter a target to search: "); t = r.readInt(); r.readLine(); int pos; pos = searchArray(a, t); if (pos == -1) System.out.println("Target not found"); else System.out.println("Target found at pos " + pos); } //end of main /* argument: an array x. This method prints all the elements in x, * in order */ public static void printArray(int[] x) { int k; k = 0; System.out.print("The array is: "); while (k < x.length) { System.out.print(x[k] + " "); k++; } System.out.println(); } //end of printArray /* argument: an array x. This method sums all the elements in x, * and returns the sum */ public static int sumArray(int[] x) { int i, sum; i = 0; sum = 0; while (i < x.length) { sum = sum + x[i]; i++; } return sum; }//end of computeSum /* argument: an array x and a target. This method searches for * target in the array x, and returns: if target is found, the * position where it is found; -1 if not found; */ public static int searchArray(int[] x, int target) { int k = 0, found = -1; while (k < x.length) { if (x[k] == target) found = k; k++; } return found; }//end of searchArray } // end of class