// Torrez, Elaine CS1A Chapter 5 P. 297, #22
/******************************************************************************************
*
* BUDGET ANALYSIS
*
* --------------------------------------------------------------------------------
* This program asks the user to enter the amount budgeted for a month and then
* prompts the user to enter their expenses one by one. The program keeps a running
* total of expenses and, when finished, displays whether the user is over or under
* budget, and by how much.
* --------------------------------------------------------------------------------
*
* INPUT
* budgetedAmount : Amount the user planned to spend for the month
* expense : Each expense entered by the user
*
* OUTPUT
* totalExpenses : The total of all entered expenses
* difference : Amount over or under budget
*
*******************************************************************************************/
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main()
{
double budgetedAmount; // INPUT - User’s monthly budget
double expense; // INPUT - Single expense value
double totalExpenses = 0; // PROCESS - Running total of expenses
char moreExpenses; // CONTROL - User’s choice to continue entering expenses
// --- Get the monthly budget ---
cout << "Enter the amount budgeted for this month: $";
while (!(cin >> budgetedAmount) || budgetedAmount < 0)
{
cout << "ERROR: Enter a positive number: $";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "\nEnter your expenses one at a time.\n";
// --- Expense input loop ---
do
{
cout << "Enter an expense amount: $";
while (!(cin >> expense) || expense < 0)
{
cout << "ERROR: Enter a positive number: $";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
totalExpenses += expense;
cout << "Do you have another expense? (Y/N): ";
cin >> moreExpenses;
}
while (moreExpenses == 'Y' || moreExpenses == 'y');
// --- Calculate difference ---
double difference = budgetedAmount - totalExpenses;
cout << fixed << setprecision(2);
cout << "\n========== BUDGET SUMMARY ==========\n";
cout << "Budgeted: $" << budgetedAmount << endl;
cout << "Spent: $" << totalExpenses << endl;
if (difference > 0)
cout << "You are under budget by $" << difference << "!" << endl;
else if (difference < 0)
cout << "You are over budget by $" << (-difference) << "!" << endl;
else
cout << "You are exactly on budget!" << endl;
cout << "====================================\n";
return 0;
}