Nic Meiring
Nic Meiring

Reputation: 882

calculating average using for loop in javascript

function averageCalculator (numvalues) {

    for(i=0, i <= numvalues, i++>) {
    var score = prompt("input the score")
    result1 += score;

    }

    alert(result1 / 3);
}

this function is later triggered by a button with onclick="averageCalculator (2)

<input type="button" value="Click for the average" onclick="averageCalculator (2)">

any ideas why its not working? it should prompt you for 2 values and then alert you with the average. not sure whats wrong.

Upvotes: 1

Views: 18636

Answers (4)

Till
Till

Reputation: 3154

Your code has multiple issues. The for loop is not well-formatted and you need to terminate statements with a semi-colon. Also, you need to declare variables. And your loop will run numvalues+1 times which is why I removed the = in your loop. Also if you want to calculate an average you want to divide by numvalues.

function averageCalculator (numvalues) {
var result1 = 0;
for(let i=0; i < numvalues; i++) {    
    var score = prompt("input the score");   
    result1 += score;    
}
alert(result1 / numvalues);
}

numvalues represents the number of inputs you want to calculate average for.

On top of the invalid syntax you will run into a common "problem" with javascript here. The inputs are treated as strings and instead of being added they will be concatenated. Providing 2 and 2 as scores will result in 11. 2 concatenated with 2 = 22 / 2 = 11. You need to cast the value to a number explicitly before adding them together:

function averageCalculator (numvalues) {
var result1 = 0;
for(i=0; i < numvalues; i++) {    
    var score = prompt("input the score");   
    result1 += Number(score);    
}
alert(result1 / numvalues);
}

The code above will correctly return 2.

Upvotes: 4

helpermethod
helpermethod

Reputation: 62234

An alternative solution (using a functional programming libary, like Underscore.js):

function averageCalculator(numValues) {
    var numbers = _.map(_.range(numValues), function(element) {
        return +prompt('input the score');
    });

    var result = _.reduce(numbers, function(memo, number) {
        return memo + number;
    }, memo);

    alert(result / 3);
}

While a little bit more complicated (and less efficient), you'll get rid of loops altogether.

EDIT

The +prompt('input the score') does effectivly the same as Number(prompt('input the score')).

Upvotes: 1

Pranav
Pranav

Reputation: 8871

Try like this

for(var i=0; i <= numvalues; i++){}

Upvotes: 1

JW.
JW.

Reputation: 2411

The syntax of your for-loop is wrong:

for(i=0, i <= numvalues, i++>) {

should be

for(i=0; i <= numvalues; i++) {

Tip: Also, it's better to use

for(var i=0; i <= numvalues; i++) {

since then i will be a local variable instead of a global one.

Upvotes: 2

Related Questions