In-class IF Exercise

We will discuss these in class. Complete the exercise with a partner, taking turns suggesting things you notice that might be improved.

Do not copy-and-paste into your editor; just read the code and think!

How can each of these C++ code segments be improved?

Code 1

    // How can this code be improved?
    const int TARGET_TEMPERATURE = 20;
    int temperature = 0;
    cout << "What is the current temperature? ";
    cin >> temperature;

    if (temperature <= 0) {
        cout << "It's freezing!" << endl;
        int difference = TARGET_TEMPERATURE - temperature;
        cout << "To be perfect, the temperature should change by " 
            << difference << " degrees!\n";
    } else {
        cout << "It's thawed!" << endl;
        int difference = TARGET_TEMPERATURE - temperature;
        cout << "To be perfect, the temperature should change by " 
            << difference << " degrees!\n";
    }

Code 2

    // How can this code be improved?
    int numVaccinesNeeded = 0;
    cout << "How many vaccines are needed? ";

    cin >> numVaccinesNeeded;
    if (numVaccinesNeeded > 1000) {
        string message = "Critical shortage";
    } else {
        string message = "Supply OK";
    }
    cout << message << ": Order " << numVaccinesNeeded << " more vaccines.\n";
    // Hint: This won't compile. Why?

Code 3

    // How can this code be improved?
    double percent = 0;
    cout << "Enter nurse's test score: ";
    cin >> percent;
    if (percent < 75.0) 
        cout << "Please have them retake the test later." << endl;
    else
        cout << "Well done!" << endl;
        cout << "Issue them a renewed license." << endl;

Code 4

    // How can this code be improved?
    double microLoan = 0;
    cout << "How much is needed for the micro loan? $";
    cin >> microLoan;

    if (microLoan < 0) {
        cout << "Loan value must be > $0.00" << endl;
    }
    if (microLoan > 100) {
        cout << "Loan value must be <= $100.00" << endl;
    } else {
        cout << "Loan approved." << endl;
    }

Code 5

    // How can this code be improved?
    double bodyTemp = 0;
    cout << "Enter patient's body temp ('C): ";
    cin >> bodyTemp;

    if (bodyTemp <= 37.0) {
        cout << "Temperature normal\n";
    }
    if (bodyTemp > 37.0) {
        cout << "Elevated temperature\n";
    }

Code 6

    // How can this code be improved?
    int age = 0;
    cout << "Enter your age: "; 
    cin >> age;
    if (age < 12) {
    cout << "I'm sorry, you can't enter this ride.\n";
    } else if (age > 100) {
    cout << "You may want to rethink this!\n";
    } else {
    cout << "Welcome!" << endl;
    }