I’m having hard time. It might be something that I didn’t learn yet maybe. Or is it with the foreach?
I got the first part right but the adding part I’m having problem
Just take a look at this W3C:JavaScript for Loop article. Try to do exactly like in the examples there.
Logic of your code have to follow next steps:
- declare a variable which will be a counter for the loop
- assign to the counter variable a start point ( zero usually: you remember all iterations in JS start from zero.)
- assign a condition for the loop. another words when the loop has to stop? what have to happen?
- every time when something happen withing your for loop you have to plus 1 to your counter.
counter = counter + 1;
or usuallycounter++
(increment). - if the condition is true something happens withing the loop (within a body of the loop). we can detect the body with
{}
. - within the body you have to increment (to add to) your
sum
variable to each value of thenumbers
array. For example:
sum = sum + 2;
sum = sum + 3;
sum = sum + 6;
…
- When the condition is false you went out of the body of the for loop and return
sum
variable which contains sum of all numbers of thenumbers
array.
for(variable; condition; increment){
something happens here;
}
1 Like