Before, we used a for loop to add up lists of numbers like 1+2+...+1000. But what if the list is less predictable, like 4+42-21+37-44? For that, we can use an array to modify that simpler sum calculator.
For example, in JavaScript:
// Input Variables
var data = [4, 42, -21, 37, -44];
// Let's add 'em up
var sum = 0;
for (var i=0; i < data.length; ++i){
sum += data[i];
}
// Let's create our message
var message = "The sum of those numbers is "+sum;
// Print and we're done
console.log(message);
data
that has the contents 1, 2, 3, 4, 5
? Demonstrate your answer with screenshots.data
variable to have the contents 21, 16, 34, -34, -29
instead. Demonstrate your answer with screenshots.For each of the following, revise your sum calculator to help you find the answer, and demonstrate with screenshots.
-46, -8, -16, 14, -29, 19, 39, 28, -40, -28
?-46
) by zero, the second item (-8
) by one, the third item (-16
) by two, and so on?