Quiz six will focus on loops.
Loops are designed to work in combination with arrays. In all of the examples below we will work with the following example array:
A = [2, -2, 1, 3, 4, 2, 5, -4, -3, 3, 4]
Here is the structure of a typical loop:
length = A.length; // Get the length of the array
for(n = 0;n < length;n = n+1) {
// 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: this code will use the syntax A[n] to refer to the current item.
1. What is the value of the variable subtotal when the following code is finished running?
subtotal = 0;
length = A.length;
for(n = 0;n < length;n = n+1) {
if(A[n] < 0)
subtotal = subtotal + A[n];
}
Answer: The purpose of the loop is to locate all of the negative numbers in A and add them up. The final value of subtotal will be -9.
2. A variable search contains a number to search for in the array A. Write the code for a loop that searches through the array to find that value. If the value appears in A, store the index where it appears in a variable location. If the number in search does not appear in the list, arrange for location to have a value of -1.
Answer:
location = -1;
length = A.length;
for(n = 0;n < length;n = n+1) {
if(A[n] == search && location == -1)
location = n;
}
3. Write a loop that searches A for all of the numbers greater than 2. Push any such numbers you find onto an array B.
Answer:
B = [];
length = A.length;
for(n = 0;n < length;n = n+1) {
if(A[n] > 2)
B.push(A[n]);
}