Search code examples
c++for-loopnested-loopsrepeat

How to repeat a "for" loop in C++


I can't figure out how to repeat this program, so the user would be able to input another set of hours.

Do I need to change this to a "Do...While" statement?

I was thinking about adding in a "User-defined function" at the end, but my professor might not allow that, since we haven't gotten there yet.

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

const float initialVolume = 130.00;
const float decreaseRate = 0.13;
string name;
int counter = 0;

int main()
{
    int hours,i,j,k;
    float remainingVolume, halfVolume, zeroVolume;

    cout << "Enter hours to see how much caffeine "
         << "is left in your body, after you drank your coffee: ";
    cin >> hours;
    cout << endl;
    cout << fixed << showpoint << setprecision(4);

    remainingVolume = initialVolume;

    for (i = 0; i < hours; i++)
    {
        counter++;
        remainingVolume = remainingVolume - decreaseRate * remainingVolume;
        cout << "Hour " << setw(5) << counter << setw(15) << remainingVolume << "mg"<< endl;
    }

    for (j = 0, halfVolume = 130.00; halfVolume > 65.0000; j++)
    {
        counter++;
        halfVolume = halfVolume - decreaseRate * halfVolume;
    }

    for (k = 0, zeroVolume = 130.00; zeroVolume > 0.0001; k++)
    {
        counter++;
        zeroVolume = zeroVolume - decreaseRate * zeroVolume;
    }

    cout << "\n" << endl;
    cout << "It will take " << j << " hours to get caffeine levels to 65mg. \n" << endl;
    cout << "It will take " << k << " hours to get caffeine levels to 0mg." << endl;

    return 0;
}

Solution

  • A simple approach that terminates if there's an error reading (e.g. the user types a non-integer value or presses e.g. ^D (Linux/UNIX) or ^Z (Windows) to generate an End-Of-File condition:

    int main()
    {
        int hours,i,j,k;
        float remainingVolume, halfVolume, zeroVolume;
    
        while (cout << "Enter hours to see how much caffeine "
                    << "is left in your body, after you drank your coffee: " &&
               cin >> hours)
        {
            cout << endl;
            cout << fixed << showpoint << setprecision(4);
            ...etc...
        }
        // no need to return 0; - that's done implicitly
    }