user13832404
user13832404

Reputation:

Compound interest in C++ without using pow function

I have been tasked to write a c++ program that finds compound interest. The trick is, I can't use the pow function and right now recursions seem way above my head. Im just starting. Can you please look at the code below and help me? Thanks. Again, I am very new to this.

I also had to use at least one while loop and can use no other loop types.

#include <iostream>


int main()
{
    // p is initial principle
    double p;
    // i is interest rate
    double i = 0.014;
    // n is number of years invested
    int n;
    // a is final amount
    double a;
    
    std::cout << "Please enter the principal amount: ";
    std::cin >> p;
    std::cout << "Please enter the number of years invested: ";
    std::cin >> n;
    
    while(n > 0)
        {
        a = ((p*i)+p);
        break;
        }
    
    std::cout << a;
    
}

Upvotes: 1

Views: 1006

Answers (1)

bartgol
bartgol

Reputation: 1873

As already pointed out, your loop is not updating n, and the break statement causes it to execute only once. If you decrement n at each iteration of the while loop, and remove the break statement, your code should work.

I want to point out, however, that when you know exactly the number of iterations of your loop, a for loop is preferable, since a) it conveys the fact that you know how many iterations you have, and b) you're less likely to run into an infinite loop.

a = p;
for (int k=0; k<n; ++k) {
  a *= 1+i;
}

Upvotes: 1

Related Questions