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

dr.bill.al
  • 33
  • 2

5 Answers5

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.

AidanM
  • 57
  • 9
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);
CryptoBird
  • 508
  • 1
  • 5
  • 22
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

Divyesh pal
  • 952
  • 1
  • 11
  • 17
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)
Abslen Char
  • 3,071
  • 3
  • 15
  • 29
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);
Ele
  • 33,468
  • 7
  • 37
  • 75