Quiz five topics

Quiz five will focus on loops and objects

Loop fundamentals

Loops are designed to work in combination with arrays. In all of the examples below we will work with the following example array:

A = [{x:20,y:30},{x:-10,y:20},{x:10,y:20},{x:20,y:20},{x:-20,y:20}]

Here is the structure of a typical loop:

var item; // Declare a variable to store an array item
for(item of A) {
  // Body of the loop
}

You can think of the loop as a mechanism for visiting each item in the array. The code in the body of the loop specifies what you want to do with that item.

Sample questions

1. What is the value of the variable subtotal when the following code is finished running?

var subtotal = 0;
var item;
for(item of A) {
  if(item.x < 0)
    subtotal = subtotal + item.x;
}

Answer: The purpose of the loop is to locate all of the objects whose x part is negative in A and add those x parts up. The final value of subtotal will be -30.

2. A variable search contains an x value to search for in the array A. Write the code for a loop that searches through the array to find the object with that x value. If such an object appears in A, store its y value in the variable value. If the x value you are searching for does not appear in the list, arrange for value to have a value of 0.

Answer:

var value = 0;
var item;
for(item of A) {
  if(item.x == search && value == 0)
    value = item.y;
}

3. Write a loop that searches A for all of the objects whose y value is greater than the items x value. Push any such objects you find onto an array B.

Answer:

B = [];
var item;
for(item of A) {
  if(item.x > item.y)
    B.push(item);
}