2
\$\begingroup\$

I am having some trouble figuring out how to modularize this code without rewriting it entirely. I know I should be able to break it up into modules for main, gathering info, doing calculation and the example sum array that's out of place, but in to meet requirements.

    #include <iostream>
    #include <iomanip> // Going to use for width and precision
    #include <cmath> // Going to use for monthly payment calc for the power function
    #include <string>
    using namespace std;

int main()
{
    // Variables Declared
    string name; // Name of user
    float loanAmt = 0; // Requested loan Amount
    int years = 0; // Loan term in years
    float interestRate = 0; // Annual APR, I think I need to take this number, divide by 100 to get decimal, and use decimal in calculations
    double months2Pay = 0; // years *12

    double interestMonthlyRate = 0; // interest rate  / 12
    double monthlyPayments = 0; // Final Monthly Payments
    double interestRateDecimal = 0; // interest rate /100
    double totalInterestPaid = 0;
    double finalTotalPaid = 0;

    char yes;
    const int loanInformation = 1, seeLoanInfo = 2, exitProgram = 3;
    int pickAChoice;

    int arrayExample[8];
    int arraySum = 0;

    cout << "\n\n     ***********************************************" << endl;
    cout << "     *                                             *" << endl;
    cout << "     *          Monthly Payment Calculator         *" << endl;
    cout << "     *                                             *" << endl;
    cout << "     ***********************************************" << endl << endl;

    cout << "Greetings and welcome to the loan calculator!\n" << endl;

    // Main Menu - options 1,2,3,4

    do
    {
        cout << "Main Menu\n\n"
        << "1. Enter loan information.\n"
        << "2. View loan results.\n"
        << "3. Adding with arrays example.\n"
        << "3. Exit\n\n"
        << "Select an option: ";
        cin >> pickAChoice;

        while (pickAChoice < loanInformation || pickAChoice > exitProgram)
        {
            cout << "Invalid selection. Please renter choice 1, 2 or 3: ";
            cin >> pickAChoice;
        }
            if (pickAChoice == 1)
        {
            // Loan Information here
            cout << "\nWhat is your name: ";
            cin >> name;
            cout << "\nTotal loan amount: $";
            cin >> loanAmt;
            cout << "\nLoan term (in years): ";
            cin >> years;
            cout << "\nInterest Rate per year: % ";
            cin >> interestRate;

            // Loan Calculations here
            interestRateDecimal = interestRate / 100;
            months2Pay = years * 12;
            interestMonthlyRate = interestRateDecimal / 12;
            monthlyPayments = (loanAmt * pow(interestMonthlyRate + 1, months2Pay) * interestMonthlyRate) / (pow(interestMonthlyRate + 1, months2Pay) - 1);
            finalTotalPaid = monthlyPayments * months2Pay;
            totalInterestPaid = finalTotalPaid - loanAmt;

            cout << "\nPlease select option 2 to view results.\n";
        }

        if (pickAChoice == 2)
        {
            // 2 decimal points for currency format in output
            cout.setf(ios::fixed); // 2 decimal points for currency format
            cout.setf(ios::showpoint);
            cout.precision(2);

            // Display results, format this nicer

            cout << endl;
            cout << "Hello " << name << "!" << " Your request loan results are below." << endl << endl;
            cout << "   Total Loan Amount: $" << loanAmt << endl << endl;
            cout << "   You will have " << months2Pay << " total payments." << endl << endl;
            cout << "   Your monthly payment is $" << monthlyPayments << endl << endl;
            cout << "   The total amount paid back is $" << finalTotalPaid << endl << endl;
            cout << "   Your total interest paid is $" << totalInterestPaid << endl << endl;
            cout << "\nTo enter different loan information, select option 1.\n";
        }

        if (pickAChoice == 3)
        {
            cout << endl;
            cout << "This will calculate the sum of all 8 of your number choices.\n\n";
            for (int x = 0; x < 8; x++)
            {
                cout << "Enter 8 intergers to calculate the sum: ";
                cin >> arrayExample[x];
                arraySum += arrayExample[x];
            }
            cout << "\nThe total sum of your 8 integers is " << arraySum << "." << endl << endl;
        }

    } while (pickAChoice != exitProgram);
    system("pause");
}
\$\endgroup\$
  • 2
    \$\begingroup\$ If you're looking for help re-writing your code, then this probably isn't the right place. If you want a review of any and all aspects of the code (perhaps, but not necessarily, with suggestions), then welcome to Code Review! \$\endgroup\$ – Toby Speight Jun 17 at 14:37
  • 2
    \$\begingroup\$ I changed the title so that it describes what the code does per site goals: "State what your code does in your title, not your main concerns about it.". Please check that I haven't misrepresented your code, and correct it if I have. \$\endgroup\$ – Toby Speight Jun 17 at 14:39
  • \$\begingroup\$ You have already basically modularized the code. You have 4 fairly well defined functions if you look at the code. If you move the large chunks of code within the if statements into functions it will be modular. Beyond this we can't help as the question is right now except to review the code as it currently exists. \$\endgroup\$ – pacmaninbw Jun 17 at 14:58
3
\$\begingroup\$

When looking at code like this, the first thing that comes to mind is the Single Responsibility Principle Every function module should be responsible for doing one thing.

In this case, you can start with main calling the function that starts the program.

You can have the string literals that you want to print to the screen as string arrays and a function that prints a string array to the screen.

Parsing the choices is easier, when done with a switch block.

Each choice should also call a function specific to that choice.

Get out of the habit of using system(). It is very insecure since there is no way to confirm that the called function will do what you expect on every machine.

\$\endgroup\$
2
\$\begingroup\$

I like your clear variable names (though I'd prefer Amount rather than abbreviating to Amt).

Avoid using namespace std - it's a big (and growing) namespace that's not intended for wholesale import like that, and doing so can unexpectedly change the meaning of your program. std:: is intentionally very short, so get used to typing it.

Don't use std::endl unless you really mean to flush the output - it's much cheaper to write a \n instead. Many of the multiline strings can be combined - e.g.

std::cout << "\n\n"
    "     ***********************************************\n"
    "     *                                             *\n"
    "     *          Monthly Payment Calculator         *\n"
    "     *                                             *\n"
    "     ***********************************************\n\n"
    "Greetings and welcome to the loan calculator!\n\n";

When reading inputs, it's vital to check that the read was successful:

cin >> name;
if (!cin) {
    std::cerr << "Invalid input\n";
    return 1;
}

Better would be to recover and re-ask for the input, but that's a little more advanced.

Does it make any sense to view results when no data have been entered? Option 2 probably shouldn't be available until option 1 has been used. In fact, it probably makes sense not to have a menu - just read the input values and produce the corresponding outputs. For multiple runs, just invoke the program again ("do one thing well").

I'm not sure what Option 3 is for - perhaps that should be a separate program?

std::system() is declared in <cstdlib>. I'd avoid it, though - how do you know the user has a program called pause in their path (I don't, for one), and how do you know it does what you expect?

\$\endgroup\$
  • \$\begingroup\$ Thank you for your response! Let me address Option 3 first, it was for a requirement to add an array to the program. I really had no idea what to do an array with, so I added it as an example for Option 3 to meet that requirement. Still don't know how to use an array here. I have been told by some programmer friends to not use using namespace std as well, basically saying the same thing you have. However, it seems like my school does want us to use it. The same with system("pause") as well, so it'll stop so I can screen shot the work. Otherwise, both would not be included. \$\endgroup\$ – Eight Jun 17 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.