1

In my script I used a for-loop to calculate the interest over an amount of money. I set the loop to 20 times. Now I'm trying to use a while-loop instead, to calculate the amount of money until the balance is doubled.

var btn = document.getElementById('btn');
var startBalance = document.getElementById('input1');
var percentage = document.getElementById('input2');
var output = document.getElementById('result');

btn.onclick = showBalance;

function showBalance() {
    var factor = 1 + percentage.value / 100;
    var newBalance = +startBalance.value * factor;
    var result = "";

    for (var i = 0; i <= 10; i++) {
        result += "Year " + i + ": €";
        result += newBalance.toFixed(2) + "<br>";
        newBalance *= factor;
    }

    output.innerHTML = result;
}

How do I use a while-loop in this case? Thank you.

0

2 Answers 2

2

Try this

var btn = document.getElementById('btn');
var startBalance = document.getElementById('input1');
var percentage = document.getElementById('input2');
var output = document.getElementById('result');

btn.onclick = showBalance;

function showBalance() {
        var factor = 1 + percentage.value / 100;
        var startingBalance = startBalance.value;
        var newBalance =+ startingBalance * factor;
        var result = "";
        var i = 0;

   while (newBalance <= startingBalance*2) {
        result += "Year " + i + ": €";
        result += newBalance.toFixed(2) + "<br>";
        newBalance *= factor;
        i++;
    }

    output.innerHTML = result;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could calculate the needed years with equation factoryears = 2 and get the final value with a while loop.

var amount = 100,
    factor = 1.02,
    i = 0,
    years = Math.ceil(Math.log(2) / Math.log(factor));

while (i++ < years) amount *= factor;

console.log('years', Math.log(2) / Math.log(factor));
console.log('total', amount);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.