0

Write a function named "count_in_range" that takes a list of numbers as a parameter and returns the number of values in the input that are between 15.3 and 42.19 not including these end points. (My code below)

function count_in_range(numbers){
    var total = 0;
    for (var i of numbers){
        if (15.3 < i < 42.19){
            total = total + 1;
        }
        return total;
    }
}

Now that I am using JavaScript, I keep on getting 1 instead of the number of values that satisfies the statement.

4
  • 1
    If you get an exercise to solve, it's because you need to learn how to solve this kind of issues. If someone here does it for you, then when will you learn how to do it? Commented Oct 5, 2018 at 14:48
  • 6
    your return statement shouldn't be in the for loop. It should be after Commented Oct 5, 2018 at 14:49
  • That is why I am asking for constructive criticism from my code. Commented Oct 5, 2018 at 14:49
  • how many times did your loop run ? Commented Oct 5, 2018 at 14:50

2 Answers 2

2
function count_in_range(numbers){
    var total = 0;
    for (var i of numbers){
        if (i > 15.3  &&  i < 42.19){
            total = total + 1;
        }

   }
return total;
}
Sign up to request clarification or add additional context in comments.

Comments

1

The problem appears to be that your return statement is short circuiting your loop. Below I have fixed this

function count_in_range(numbers){
    var total = 0;
    for (var i of numbers){
        if (15.3 < i < 42.19){
            total = total + 1;
        }
    }
    return total;
}

2 Comments

I am getting the total input instead of the input that satisfies the statement.
see Chayan's answer

Your Answer

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