Ad

Using While- Loops Instead Of For-loops In Javascript

- 1 answer

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.

Ad

Answer

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;
}
Ad
source: stackoverflow.com
Ad