Group D

Q7: Write a C++ program to use the map associative container. The keys will be the names of states, and the values will be the populations of the states. When the program runs, the user is prompted to type the name of a state. The program then looks in the map, using the state name as an index, and returns the population of the state. Include error handling for cases where the state name does not exist in the map.

Map Container

Solution and implementation for Q7 from Object-Oriented Programming (oop).

grpD_7.c++ Download
#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, long long> statePopulation = {
        {"Uttar Pradesh", 231502578},
        {"Maharashtra", 123144223},
        {"Bihar", 127104093},
        {"West Bengal", 100671234},
        {"Madhya Pradesh", 84935639}
    };

    string stateName;
    cout << "Enter the name of the state to find its population: ";
    getline(cin, stateName);

    if (statePopulation.find(stateName) != statePopulation.end()) {
        cout << "The population of " << stateName << " is " << statePopulation[stateName] << "." << endl;
    } else {
        cout << "State not found." << endl;
    }

    return 0;
}

Other Questions in Object-Oriented Programming

See All Available Questions
Download