181k views
3 votes
In this lab, you use what you have learned about searching an array to find an exact match to complete a partially prewritten C program. The program uses an array that contains valid names for 10 cities in Michigan. You ask the user to enter a city name; your program then searches the array for that city name. If it is not found, the program should print a message that informs the user the city name is not found in the list of valid cities in Michigan. The file provided for this lab includes the input statements and the necessary variable declarations. You need to use a loop to examine all the items in the array and test for a match. You also need to set a flag if there is a match and then test the flag variable to determine if you should print the the Not a city in Michigan. message. Comments in the code tell you where to write your statements. You can use the previous Mail Order program as a guide. Instructions Ensure the provided code file named MichiganCities.cpp is open. Study the prewritten code to make sure you understand it. Write a loop statement that examines the names of cities stored in the array. Write code that tests for a match. Write code that, when appropriate, prints the message Not a city in Michigan.. Execute the program by clicking the Run button at the bottom of the screen. Use the following as input: Chicago Brooklyn Watervliet Acme

1 Answer

6 votes

Final answer:

To complete this lab task, you need to write a loop that examines each city name in the array and compares it to the input city. If a match is found, a flag variable is set to true; otherwise, a message is printed stating that the city is not in Michigan.

Step-by-step explanation:

To solve this lab task, you need to write a loop that examines each city name in the array. Inside the loop, you should compare the input city name to each city name in the array using an if statement. If a match is found, set a flag variable as true. After the loop, check the flag variable to determine if a match was found. If the flag is false, print the message 'Not a city in Michigan'.

Here's an example of how you can implement this:

string cities[] = {"Detroit", "Ann Arbor", "Lansing", "Grand Rapids", "Flint", "Kalamazoo", "Dearborn", "Troy", "Livonia", "Novi"};
string inputCity;
bool matchFound = false;

cout << "Enter a city name: ";
cin >> inputCity;

for (int i = 0; i < 10; i++) {
if (inputCity == cities[i]) {
matchFound = true;
break;
}
}

if (matchFound) {
cout << inputCity << " is a city in Michigan." << endl;
} else {
cout << inputCity << " is not a city in Michigan." << endl;
}

User Kopi Bryant
by
6.0k points