Home > Mobile >  Making a loop for calculating compound interest in JS
Making a loop for calculating compound interest in JS

Time:06-13

brand new to code and I am currently doing the pre-course work for a coding bootcamp at GA.

This work is timed and I've hit a snag while trying to complete one of the challenges.

So far we have only gone over the very basics and have just touched upon loops (For and While).

The challenge in JavaScript that has me stumped goes as follows:

You recently invested $1,000 into cryptocurrency. Good luck! Using a for loop and a conditional, log the value of your investment throughout the next 10 years by using the following rules:

Each year, the investment increases by 10%. Add 10% to the investment variable before logging the value. In the seventh year, the investment loses 75% instead of increasing. Eeek!

Use a for loop to log how many years it has been and how much the investment is worth for each year. Your logs should look like this:

Years: 1 Value: 1100 Years: 2 Value: 1210

The first line in JS is completed and it has named a var: 'let investment = 1000;'

I am completely thrown off here and have a few ideas but nothing I can think of seems to cover all the bases, especially the year 7 ordeal.

I know what i've been writing so far is NOT right, but I will include it below so you can understand my thinking here:

let investment = 1000 * 1.1^years; for (let years = 1; years < 11 && !== 7; if years === 7 {investment *.25}; years ) {console.log("Years: " years " Value: " investment);

Any helps or tips to point me in the right direction would be very much appreciated. TIA - Cbenks.

CodePudding user response:

simple loop, index variable, years and investment as input. output at the end of each loop, and if its the 7th year then it will deduct 75% of the investment value, etc..

let investment = 1000;
let years = 10;

for(let i=0;i<years;i  ){
    if(i == 6){
      investment = investment * 0.75;
    } else {
        investment = investment * 1.10;
    }
    console.log("Years: "   (i   1)   " Value: "   investment)
}

CodePudding user response:

Here is one solution:

balance = 1000

for (let i = 1; i < 10; i  ) {

if (i == 7){
growth = 0.25}
else{
growth = 1.1;
}

balance = balance * growth;

balance = Math.round(balance)
console.log(i, balance)
}

You are using the "^" character, which I don't think works as an exponent is JS, the equivalent would be "**" or pow(), but since they want you to lose a loop, the implication is that they want multiplication.

  • Related