Segwayinto
Segwayinto

Reputation: 127

In JavaScript, how to have the code add up randomly generated numbers one by one as it goes through a for loop?

for (var i = 1; i <= 10; i++) {
    console.log(1 + Math.floor(Math.random() * 100));
}

The code above returns a random number between 1 and 100 ten times over, but I can't figure out how to have the code add up those ten numbers one by one as it goes through the loop.

I'm not talking about adding them all up at once after getting out of the for loop. Any suggestions would be appreciated.

Upvotes: 0

Views: 44

Answers (2)

Ajwhiteway
Ajwhiteway

Reputation: 1006

You will need to introduce variables to do what you are looking for. This should do it if I understand correctly.

var runningTotal = 0;

for (var i = 1; i <= 10; i++) {
    var randomNumber = 1 + Math.floor(Math.random() * 100);
    console.log(randomNumber);
    runningTotal += randomNumber;
    console.log(randomNumber);
}

Upvotes: 0

adeneo
adeneo

Reputation: 318212

Just add them up inside the loop?

var added = 0;

for (var i = 1; i <= 10; i++) {
    var rand = (1 + Math.floor(Math.random() * 100));

    added += rand;
}

FIDDLE

Upvotes: 1

Related Questions