How do I eliminate the need for vectors?

I had some help coming up with this answer to a problem thus far, but it's not quite what I need. How would I rewrite this code without the use of arrays? Any advice would be greatly appreciated! Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <iostream>
using namespace std;
double CalculateTotalLoanAmount(double amount,double interest,double monthlyPayment)
    {
        double totalPaid=0.0;
        double interestRate=interest/1200;
        double monthlyInterest;
        while(amount>0)
        {
            monthlyInterest=interestRate*amount;
            amount=amount+monthlyInterest;
            if(amount>=monthlyPayment) 
            {
                amount=amount-monthlyPayment;
                totalPaid=totalPaid+monthlyPayment;
            }
            else
            {
               totalPaid=totalPaid+amount;
                amount=0;
            }  
         }
        return totalPaid;
    }
       double checkMonthlyPayment(double amount,double interest)
    {
        double monthlyPayment;
        double interestRate=interest/1200;
        cin>>monthlyPayment;
       while(monthlyPayment<(interestRate*amount))
        {
            cout<<"Amount entered is insufficient to cover interest. Please enter a new amount: \n"; 
            cin>>monthlyPayment;
         }
       return monthlyPayment;
      }

void compareLoans(double amount[],double interest[],double monthlyPayment[],double total[])
{
    cout<<"\nThe difference in the amount borrowed is: ";
    if(amount[0]>amount[1])
    cout<<amount[0]-amount[1];
    else
    cout<<amount[1]-amount[0];
    cout<<"\nThe difference in the interest rates is :";
    if(interest[0]>interest[1])
    cout<<interest[0]-interest[1];
    else
    cout<<interest[1]-interest[0];
    cout<<"\nThe difference in the amount paid per month is: ";
    if(monthlyPayment[0]>monthlyPayment[1])
    cout<<monthlyPayment[0]-monthlyPayment[1];
    else
    cout<<monthlyPayment[1]-monthlyPayment[0];
    cout<<"\nThe total amount paid for the first loan is : ";
    cout<<total[0];

    cout<<"\nThe total amount paid for the second loan is : ";
    cout<<total[1];
    cout<<"\nThe difference in the total amount paid for the loans is : ";
    if(total[0]>total[1])
    cout<<total[0]-total[1];
    else
    cout<<total[1]-total[0];
}

int main() 
{
    double amount[10];
    double interest[10];
    double monthlyPayment[10];
    double total[10];
    int i;
 
    for(i=0;i<2;i++)
    {
        cout<<"Enter Details for Loan "<<i+1<<"\n";
        cout<<"\nEnter Amount to be borrowed: ";
        cin>>amount[i];
        cout<<"\nEnter the Annual Interest rate: ";
        cin>>interest[i];
        cout<<"\nEnter Monthly Payment: ";
      
        
        monthlyPayment[i]=checkMonthlyPayment(amount[i],interest[i]);
        total[i]=CalculateTotalLoanAmount(amount[i],interest[i], 
        monthlyPayment[i]);
    }
    compareLoans(amount,interest,monthlyPayment,total);

  return 0;
}


Last edited on
How do I eliminate the need for vectors?


How would I rewrite this code without the use of arrays?


Vectors are what one uses instead of arrays. Doing it without either seems very odd, and will be a real pain. Very awkward.

Any advice would be greatly appreciated!

Just use vectors.

All that aside, what's your motivation here? Doing it without vectors, and without arrays, will make the code longer and harder to read and more likely to have bugs and harder to maintain. It's just a bad idea all round, so what's the motivation?
Since you only seem to use some_array[0] and some_array[1], just make those two separate variables for each array you currently have. And instead of passing in the double the_array[], pass in double item1, double item2.
That being said, judging by the initial for loop, it looks like your program would be fine with using arrays/vectors, so I don't see why you want to get rid of them.
I would make it a habit to add .0 to all double constants. its not a bug in your code that I see, but if you are not in the habit of it, you can accidentally do integer math.

another answer is that you can replace arrays/vectors with a different container, like a class/struct in your case or a container class (list, tree, map, etc).

your motivation and need is unclear, making it hard to answer.
I misspoke when I said vectors. While I understand it is easier to use arrays in this instance, the assignment is to use two functions and a loop, not arrays. I was unaware of this fact as we covered arrays in the course but only after this assignment was assigned. So, I need to find a way to rewrite it without the arrays and I was hoping I could get some advice as to how to go about this. If needed for further clarification, I can post the full details of the assignment here:


**We want a program which will compare the two loans. The program will get the following information about the first loan:
• The amount to be borrowed (for example 1000.00)
• The annual interest rate (for example 12 for twelve percent per year)
• The amount to be paid per month
For each loan, the program will start by asking how much will be borrowed and storing the reply as this amount. Next, the program will ask what the annual interest rate will be and it will store this amount divide A function will be used to get a valid amount for the monthly payment. The amount returned will be a double which has been checked by the function to ensure that it is not too small to eventually pay off the loan. The function will be passed the amount borrowed and the yearly interest percentage. The annual rate is divided by 12 to get the monthly rate. For example, 12 percent per year will be .01 per month. The function will find out the amount of interest paid for the first month by multiplying the amount borrowed by the monthly interest rate. When the user enters the amount to be paid per month, there will be a loop which compares the amount of interest for the first month with the monthly payment. If the monthly payment is not more than the interest for the first month, a message is displayed and the user is asked to enter a larger monthly amount. (Otherwise, the loan could never be paid off.)
The program will call another function which will calculate the total amount paid on the loan and return that value. This function will be passed the amount borrowed, the monthly payment amount, and the annual interest rate. It returns the total amount paid as a double.
Next, the program will get the same information for the second loan and use the same functions to calculate the total amount paid on the second loan. Note that different sets of arguments are passed to the functions for the new calls.
Finally, the following information is displayed:
• The difference in the amount borrowed (i.e. the amount of the first loan minus the amount borrowed for the second loan).
• The difference in the interest rates.
• The difference in the amount paid per month
• The total amount paid for the first loan.
• The total amount paid for the second loan.
• The difference in the total amount paid for the loans.
The function which calculates the total amount paid for a loan works as follows. It sets up its local variables. Then it begins a loop to calculate how much money it will take. The total paid variable will keep track of the sum of the monthly payments. The loop will keep cycling until the amount of the loan is reduced to zero. Each month (each cycle) the amount of the loan is increased by the amount of the interest charge (this interest charge changes each month). The amount of the loan is reduced by the monthly payment or the amount owed, which ever is lower. The total paid is increased by the amount paid this month. Note that the last payment will probably be only the amount remaining to be paid, not the usual monthly amount. When the amount of the loan is reduced to 0, the function returns the total amount paid.**

I apologize for any for my initial post being somewhat vague and lacking in pertinent information. This is the first time I have posted on here and wasn't sure what all to include.
Last edited on
Where in that problem description does it say you can't use arrays?
Well, it doesn't explicitly say that, but this assignment is from a chapter before arrays were covered, so I'll lose points if I don't stick to the what's covered in the chapter.
if you're only using indices 0 and 1, why do you even need arrays...? LoanA variables, LoanB variables
The array setup in my code were suggested from a tutor on tutor.com. But if I have loanA and loanB variables, would I need a separate function for each loan? And if so, how do I go about comparing them? Or do I simply need to replace the 0s and 1s with the loanA and loanB variables? I tried rewriting it declaring separate variables for each loan previously and couldn't get it to compile. That's when I asked for assistance. Should I rewrite it entirely? I feel like this should be easier than what I've made. It definitely should be. But I got to this point and I'm just trying to make it work within the parameters set by my professor without scrapping the whole thing.
Primarily, I am struggling with this part:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for(i=0;i<2;i++)
    {
        cout<<"Enter Details for Loan "<<i+1<<"\n";
        cout<<"\nEnter Amount to be borrowed: ";
        cin>>amount[i];
        cout<<"\nEnter the Annual Interest rate: ";
        cin>>interest[i];
        cout<<"\nEnter Monthly Payment: ";
      
        
        monthlyPayment[i]=checkMonthlyPayment(amount[i],interest[i]);
        total[i]=CalculateTotalLoanAmount(amount[i],interest[i], 
        monthlyPayment[i]);
    }
    compareLoans(amount,interest,monthlyPayment,total);


If I remove the arrays, what do I need to do to this to make it compile? It needs to compare the two loans and display the differences between them. It needs to use the same function for both loans.
I mentioned this before.
Get rid of the for loop, and then instead of variable_name[i], where i will be equal to 0 and then 1, just make two variables, you can call them "variable0" and "variable1".

For example, instead of
double monthlyPayment[10];
have two variables,
1
2
    double monthlyPayment0;
    double monthlyPayment1;

and maybe give them more meaningful names.

Then, do
monthlyPayment0 = checkMonthlyPayment(amount0, interest0);

monthlyPayment1 = checkMonthlyPayment(amount1, interest1);

Instead of passing in an array, you have to pass in both variables

compareLoans(amount, ...);
becomes
compareLoans(amount0, amount1, ...);

You have to apply this to each variable you have as an array, turning it into two separate variables instead.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <iomanip>

using namespace std;

void PromptInfo(double& amount, double& interest, double& monthly, double& total)
{
    cout << "Amount (e.g. 1000.0)? ";
    cin >> amount;
    cout << "Interest percentage (e.g. 12)? ";
    cin >> interest;

    double min_monthly = amount*interest/100.0/12.0;
    do
    {
        cout << "Monthly payment? (minimum >"<<min_monthly<<")? ";
        cin >> monthly;
    }
    while (monthly<=min_monthly);

    // Calculating total
    total = 0.0;
    double amt = amount*(1+interest/100.0/12.0);
    while (amt >= monthly)
    {
        amt -= monthly;
        total += monthly;
        amt *= (1+interest/100.0/12.0);
    }
    total += amt;
}

int main() 
{
    cout << fixed << setprecision(2);
    double a_amount, a_interest, a_monthly, a_total;
    double b_amount, b_interest, b_monthly, b_total;
    cout << "Please enter info for loan A.\n";
    PromptInfo(a_amount, a_interest, a_monthly, a_total);
    cout << "\n\nPlease enter info for loan B.\n";
    PromptInfo(b_amount, b_interest, b_monthly, b_total);

    cout << "\n\nStats for loans A and B:\n" << 
            "  Amount Difference:   $" << (a_amount-b_amount) << '\n' <<
            "  Interest Difference:  " << (a_interest-b_interest) << "%\n" <<
            "  Monthly Difference:  $" << (a_monthly-b_monthly) << '\n' <<
            "  A Total Paid:        $" << a_total << '\n' <<
            "  B Total Paid:        $" << b_total << '\n' <<
            "  Total Difference:    $" << (a_total-b_total) << '\n';

    return 0;
}


running at https://repl.it/@icy_1/BronzeTechnicalCron

Possible output:
Please enter info for loan A.
Amount (e.g. 1000.0)?  1000
Interest percentage (e.g. 12)?  12
Monthly payment? (minimum >10.00)?  11


Please enter info for loan B.
Amount (e.g. 1000.0)?  2000
Interest percentage (e.g. 12)?  12
Monthly payment? (minimum >20.00)?  21


Stats for loans A and B:
  Amount Difference:   $-1000.00
  Interest Difference:  0.00%
  Monthly Difference:  $-10.00
  A Total Paid:        $2650.85
  B Total Paid:        $6425.41
  Total Difference:    $-3774.56
Thank you, icy1! I had to make some adjustments (to better conform to the assignment and also to feel like I maintained some integrity by not using your code verbatim) but all-in-all your code was fantastic and a huge help. I greatly appreciate your help and everyone else who commented.
Last edited on
no problem; was fun ;D. Use as much as you want.

I should note, for future readers, too, that the technique used here is references . The variables are owned by main() and passed in by reference to the method (shown by the ampersand in method signature). When the method changes these variables, the changes are reflected in main().

This is particularly useful when you need to return many things back to the caller.

Other stuff you can add:
- error handling for bad input
- output the number of months it'll take to repay (add a counter in the while loop during total calculation)
Last edited on
Topic archived. No new replies allowed.