2

I have a blank array and i need to add the numbers from 1 to 20 to this array. After that i need to sum these number totally. I am stucked in here:

for(i=1;i<=20;i++){ push() } 

What do you think, please answer. Thank you

4

5 Answers 5

1

Let's see... First you need to define an array like so:

var array =[]; 

And you also need to make a variable for the sum:

var sum = 0; 

Now you use that for loop to add your numbers to the array:

for(var i = 0; i <= 20; i++) { array[i] = i; sum += i; } 

Hopefully this is what you were looking for.

Sign up to request clarification or add additional context in comments.

4 Comments

From OP: i need to sum these number totally.
Yeah, forgot to add that. Updated my answer accordingly!
arrays are zero based. what happens to index zero?
Guess I typed var i = 1 instead of 0. Thanks for pointing that out!
0

yeah you can achieve it simply just by making a push() function to the array variable like:

<script> function helloWorld(){ var arr = Array(); var sum = 0; for(var i=0;i<20;i++){ arr.push(i+1); sum = sum+(i+1); } console.log(arr,sum); } </script> 

in the console.log you will get the result

Comments

0

another way to do it is with the use of reduce

 var arr = []; for(i=1;i<=20;i++){ //a for loop to create the array arr.push(i) } console.log("the value of the array is " + arr) var sum = arr.reduce(add, 0); function add(a, b) { // a function the calculate the total return a + b; } console.log("the total is " + sum) 

Comments

0

If I got your question correctly, this should help :

var i = 1, sum = 0, numbers = []; // Filling the array : for(i=1; i<=20; i++){ numbers.push(i); } // Calculating the sum : numbers.forEach(function(number) { sum += number; }); 

And to see the result :

alert(sum); 

Comments

0

This is an alternative using the function Array.from to initialize and the function reduce to sum the whole set of numbers.

var numbers = Array.from({length: 20 }, () => ( this.i = ((this.i || 0) + 1 )) ); //0,1,2,3.... and so on! sum = numbers.reduce((a, n) => a + n, 0); console.log(sum);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.