Program: Linear search through a 1D array, counting matches



Searches through a 1D array of string values, counting successful hits.

Can compile and run on a Raspberry Pi, Apple Mac or Linux PC. Alternatively paste the code into repl.it

Code below:

// Linear search example
// Find multiple occurrences in a 1D array
// Phil Gardner

#include <iostream>
using namespace std;

int main()
{
const int NUM_ITEMS = 10;
string flight[NUM_ITEMS];

flight[0] = "Glasgow";
flight[1] = "Manchester";
flight[2] = "Berlin";
flight[3] = "Paris";
flight[4] = "Manchester";
flight[5] = "Moscow";
flight[6] = "Berlin";
flight[7] = "Glasgow";
flight[8] = "Paris";
flight[9] = "Manchester";

// --------------------

string target;
int times_found, index;

    // Infinite loop - repeatedly ask user for a destination to search for
do
    {
        cout << endl << "Find which city? ";
        cin >> target;

        cout << "Searching... ";

        // Perform the linear search
        times_found = 0;

        for (  index = 0;  index < NUM_ITEMS;  index++  )
            if ( flight[index] == target )
                times_found = times_found + 1;
        // end of linear search

        // Report the results
        if ( times_found > 0 )
            cout << "Found " << times_found << " flights.";
        else
            cout << "No flights found.";

        cout << endl << endl;

    } while ( true );
}