Lab 6: Sum Redux

In this hands-on activity we will return to our earlier "sum calculator" and improve it to use arrays.

Example

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);

Questions

Part 1

  1. Answer for each language: Does your language (by default) use fixed-length or dynamic-length arrays?
  2. What are some of the major differences between fixed-length and dynamic-length arrays? Pros and cons of each?
  3. Answer for each language: What is the syntax in your language for creating an array literal? How would you use this to create an array named data that has the contents 1, 2, 3, 4, 5? Demonstrate your answer with screenshots.
  4. An array has 100 items in it. What is the index of the first item in this array? The second item? The last item?
  5. According to the book, what does the phrase "out of bounds" mean when refering to arrays?
  6. Answer for each language: How do you get the length of an array in your language? How would you use this to display a message like "The size of the data array is..."? Demonstrate your answer with screenshots.
  7. Answer for each language: How would you display the contents of an array in your language using a for loop? How would you use this to display the contents of the data array mentioned above? Demonstrate your answer with screenshots.
  8. When speaking about dynamic-length arrays in general, what do we mean when we say "push" (sometimes "append")? What do we mean when we say "pop"?
  9. When speaking about fixed-length arrays in general, what do we mean when we say "initialize"? What do we mean when we say "populate"?

Part 2

  1. Pick one language from your group. What language did you choose for this task and why?
  2. In your chosen language, program the sum calculator described above. Change the value of the data variable to have the contents 21, 16, 34, -34, -29 instead. Demonstrate your answer with screenshots.

Part 3

For each of the following, revise your sum calculator to help you find the answer, and demonstrate with screenshots.

  1. What is the sum of the list -46, -8, -16, 14, -29, 19, 39, 28, -40, -28?
  2. What is the mean of that list instead?
  3. What is the mean of that list if we multiply the first item (-46) by zero, the second item (-8) by one, the third item (-16) by two, and so on?