Array Worksheet II Answers

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


2.  int match(int[],int[],int);


3.  int first[25],second[25];
    cout << "Enter the first 25 numbers: ";
    for (i = 0 ; i < 25 ; i++)
       cin >> first[i];
    cout << "Enter the next 25 numbers: ";
    for (i = 0 ; i < 25 ; i++)
       cin >> second[i];
    cout << "There were " << match(first,second,25)
                          << " matches in the two arrays\n";


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


5.  int count(char[],char int);


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


7.  int search(int arr[],int size,int value)
    {
       int found;
       int i;
       for (i = 0, found = 0 ; i < size ; i++)
          if (arr[i] == value)
             found = 1;
       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:

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


8.  int search(int[],int,int);


9.  exists = search(salaries,100,1500);
    if (exists == 1)       //  could also write "if (exists)"
       cout << "The value 1500 was found in the array salaries\n";
    else
       cout << "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 2002