0

Hey guys I want to create a function that takes in an array and returns true if the array is an arithmetic series and returns false if it is not. My problem is my for loop is looping through each pair to see if each consecutive pair is divisible by the difference of the first two elements. As a consequence, I am stuck and can only create a function that returns true 4 times when I do have a arithmetic series. Does anyone know how to alter my code so that I only get true or false. Here's what I have:

function arithseries(arr){
    var arit = arr[1] - arr[0];
    for(var i = 0; i < (arr.length - 1); i++){
        if((arr[i + 1] - arr[i]) % arit === 0){
            console.log("true");
            }
        else{
            console.log("false")
        }
        }
    }


arithseries([2,4,6,8,10])

returns

=> true
=> true
=> true
=> true

1 Answer 1

1
function arithseries(arr) {
    var arit = arr[1] - arr[0];
    for (var i = 0; i < (arr.length - 1); i++) {
        if ((arr[i + 1] - arr[i]) % arit !== 0){
            return false
        }
    }

    return true
}


console.log(arithseries([2,4,6,8,10]))
Sign up to request clarification or add additional context in comments.

3 Comments

Why did you remove else?
In the else branch you'd actually say 'okay, everything fine so far - continue testing'. You check each element and as soon as one is wrong, you return false (series not correct). When you checked all elements (i.e. after the for loop) you know that the series is valid and return true. No need for an else anywhere since the loop will continue anyway.
Right, but what if the if conditional returns false once the loop has stopped wont it also move on from the for loop and return true as well?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.