0

I have an exercise to create a function (lets call it "iterateAndSum") which will sum all numbers in array and return the result. I can't use reduce (which is easier). I have to focus on using while loop.

I tried and failed miserably:

function iterateAndSum(arr) {
    while (i--) {
        e += arr[i]; 
    }
}
0

3 Answers 3

1
function iterateAndSum(arr) {
  let i = 0;
  let e = 0;
  while (i < arr.length) {
    e += arr[i];
    i++;
  }
  return e;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, But i can not use reduce, i have to focus on a "while" loop. Is anyway to do so?
1

const arr = [1,2,3];
let i = 0;
let sum = 0;
while(i<arr.length) {
  sum+=arr[i];
  i++;
}

//sum = 6
console.log(sum); 

Comments

1

function iterateAndSum(arr) {
  let e = 0,i=0;
  while (i < arr.length) {
      e += arr[i++]; 
  }
  return e
}

let result = iterateAndSum([5,9,6,2,8,0,4])

console.log(result)

Comments

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.