Brian
Brian

Reputation: 5

Using a for loop to calculate interest

Okay so i am attemtping to make a calculator that calculates interest on the principal over a course of time for instance 10 years. The principal is 100,000 the interest rate is .08% So far my code works and doesnt throw errors but it only displays the first year and wont display the other 9. What am I not seeing here?

function interest(){
    var investment = 100000;
    var rate = .08;
    var text = "";
    var amount = 100000 * (1.0 + .08 * 1);
    var year = new Array(12);
    var i ;
    for (i=0; i < year.length; i++) {
        text += "The total to date is " + "$" + i + "<br>";
        year[i] = i+investment;
    }
    document.getElementById("demo").innerHTML = text;
    document.getElementById("demo").innerHTML = amount;
}

Upvotes: 0

Views: 3095

Answers (2)

Burak Ozdemir
Burak Ozdemir

Reputation: 5332

I'm not sure with your calculation but the reason that you don't get the other 9 is that when you use innerHTML, you overwrite the current. So in the first line, you set the innerHTML as text, but after that, you overwrite it as amount, that's why you don't see the years.

document.getElementById("demo").innerHTML = text + amount;

And i guess what you are trying to do is something like below with the calculation:

function interest(){
    var investment = 100000;
    var rate = .08;
    var text = "";
    var year = new Array(12);
    for (var i=1; i <= year.length; i++) {
        text += "The total will be in "+i+" years is " + "$" + (investment * ( 1 + (i * rate))) + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
}

Check the demo below:

http://jsfiddle.net/d6w7yefL/3

Upvotes: 1

dshun
dshun

Reputation: 223

remove the 2nd line

document.getElementById("demo").innerHTML = amount;

see this:

    var investment = 100000;
    var rate = .08;
    var text = "";
    var amount = 100000 * (1.0 + .08 * 1);
    var year = new Array(12);
    var i ;
    for (i=0; i < year.length; i++) {
    text += "The total to date is " + "$" + i + "<br>";
    year[i] = i+investment;
    }

    document.getElementById("demo").innerHTML = text;
    //document.getElementById("demo").innerHTML = amount;

http://jsfiddle.net/dshun/w9x7zk5d/

Upvotes: 0

Related Questions