fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. int main() {
  6. // Ask for input
  7. double annual_interest_rate, starting_balance;
  8. int months_passed;
  9. cout << "Enter the annual interest rate: ";
  10. cin >> annual_interest_rate;
  11. cout << "Enter the starting balance: ";
  12. cin >> starting_balance;
  13. cout << "Enter the number of months that have passed: ";
  14. cin >> months_passed;
  15.  
  16. // Initialize variables
  17. double balance = starting_balance;
  18. double total_deposits = 0, total_withdrawals = 0, total_interest = 0;
  19.  
  20. // Loop for each month
  21. for (int i = 1; i <= months_passed; i++) {
  22. // Ask for input
  23. double deposit, withdrawal;
  24. cout << "\nMonth " << i << "\n";
  25. cout << "Enter the amount deposited: ";
  26. cin >> deposit;
  27. while (deposit < 0) {
  28. cout << "Amount must be non-negative. Enter again: ";
  29. cin >> deposit;
  30. }
  31. cout << "Enter the amount withdrawn: ";
  32. cin >> withdrawal;
  33. while (withdrawal < 0) {
  34. cout << "Amount must be non-negative. Enter again: ";
  35. cin >> withdrawal;
  36. }
  37.  
  38. // Update balance and totals
  39. balance += deposit - withdrawal;
  40. total_deposits += deposit;
  41. total_withdrawals += withdrawal;
  42.  
  43. // Calculate interest
  44. double monthly_interest_rate = annual_interest_rate / 12;
  45. double monthly_interest = balance * monthly_interest_rate;
  46. total_interest += monthly_interest;
  47. balance += monthly_interest;
  48.  
  49. // Check if account has been closed
  50. if (balance < 0) {
  51. cout << "\nYour account has been closed due to a negative balance.\n";
  52. break;
  53. }
  54. }
  55.  
  56. // Display results
  57. cout << fixed << setprecision(2);
  58. cout << "\nEnding balance: $" << balance << endl;
  59. cout << "Total deposits: $" << total_deposits << endl;
  60. cout << "Total withdrawals: $" << total_withdrawals << endl;
  61. cout << "Total interest earned: $" << total_interest << endl;
  62.  
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0.01s 5532KB
stdin
10%
10000
36
500
200
stdout
Enter the annual interest rate: Enter the starting balance: Enter the number of months that have passed: 
Month 1
Enter the amount deposited: Enter the amount withdrawn: 
Your account has been closed due to a negative balance.

Ending balance: $-0.00
Total deposits: $0.00
Total withdrawals: $0.00
Total interest earned: $-0.00