Shay Harris
Shay Harris

Reputation: 1

How would I use a while loop?

ask how many expenses they have for the month. Loop (using a for-loop) for each of these expenses, asking how much they spent on each one. Numbering for expenses should display for the user starting at one. Keep a running track of how much they're spending as you're looping.

For each expense, verify that the expense costs at least $0.01 in a loop (using a while-loop).

They shouldn't be able to move on until they've entered in a valid expense.

Here is the code shown below. when I input 0 just to see if the while loop works, it doesn't work. Any suggestions?

int main()
{ 
    // Variables // 
    double monthlyIncome, monthlySave, monthlyBudget, ex_cost = 0.01, ex_num;
    int expenseMonth;

    // A warm welcome message//
    cout << "Welcome to the budget calculator" << endl;

    // user puts in monthly income and how much they would like to save//
    cout << "Please enter your starting monthly income: ";
    cin >> monthlyIncome;
    cout << "Please enter how much you would like to save: ";
    cin >> monthlySave; 

    //Calculating and outputting  monthly budget//
    monthlyBudget = monthlyIncome - monthlySave;
    cout << "Your monthly budget is: $" << monthlyBudget << endl;

    // user inputs expense number //
    cout << "How many expenses did you have this month: ";
    cin >> expenseMonth;

    // loop for expenses //
    for (int i = 1; i <= expenseMonth; ++i) {
        cout << "How much did you spend on expense " << i << ":" <<endl;
        cin >> ex_num;
        while (ex_num <= 0.01) {
            cout << "you must have spent at least 0.01 for it to be an expense!" << "Please try again" << endl;
        }
    }

Upvotes: 0

Views: 133

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595320

Your while loop is checking the same expense value over and over without giving the user a chance to change the value if it is not valid, thus it gets stuck in an endless loop.

Also, you are not allowing expenses to be at least 0.01 like the instructions ask for.

Try this instead:

for (int i = 1; i <= expenseMonth; ++i) {
    cout << "How much did you spend on expense " << i << ":" <<endl;
    cin >> ex_num;
    while (ex_num < 0.01) { // <-- needs to be < not <= !
        cout << "you must have spent at least 0.01 for it to be an expense! Please try again" << endl;
        cin >> ex_num; // <-- add this!
    }
}

Personally, I would use a do..while loop instead, since the input has to be read in at least 1 time, eg:

for (int i = 1; i <= expenseMonth; ++i) {
    do {
        cout << "How much did you spend on expense " << i << ":" <<endl;
        cin >> ex_num;
        if (ex_num >= 0.01) break;
        cout << "you must have spent at least 0.01 for it to be an expense! Please try again" << endl;
    }
    while (true);
}

Upvotes: 2

Related Questions