Third Array Worksheet Answers

1.  public static int match(int one[], int two[]) {
       int k, count = 0;
       for (k = 0; k < one.length; k++)
          if (one[k] == two[k])
             count++;
       return count;
    }


2.  int[] first = new int[25];
    int[] second = new int[25];
    System.out.println("Enter the first 25 numbers: ");
    for (i = 0 ; i < 25 ; i++)
       first[i] = keybd.nextInt();
    System.out.println("Enter the next 25 numbers: ");
    for (i = 0 ; i < 25 ; i++)
       second[i] = keybd.nextInt();
    System.out.println("There were " + match(first,second,25)
                          + " matches in the two arrays\n");


3.  public static int count(char letters[], char find, int size) {
       int j, numfound = 0;
       for (j = 0; j < size; j++)
          if (letter[j] == find)
             numfound++;
       return numfound;
    }


4.  int let[12] = {'f','A','i','@','N','Z','a','7','p','Y','h','A'};
    System.out.println("There were " + count(let,'p',12) + "p's in the array\n";


5.  public static boolean search(int arr[],int size,int value) {
       boolean found;
       int i;
       for (i = 0, found = false ; i < size ; i++)
          if (arr[i] == value)
             found = true;
       return found;
    }

    Notice that this keeps searching the array even after the value
    is found. We could stop searching once we find the value - here
    is a version that does that:

    public static boolean search(int arr[],int size,int value) {
       boolean found;
       int i;
       for (i = 0, found = false ; i < size && !found; i++)
          if (arr[i] == value)
             found = true;
       return found;
    }


6.  exists = search(salaries,100,1500);
    if (exists == true)       //  could also write "if (exists)"
       System.out.println("The value 1500 was found in the array salaries\n");
    else
       System.out.println("The value 1500 was not found in the array salaries\n");

Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2013