COP 2500 Spring 2012Lab #5 |
| Home | Labs | Lecture Notes |
|
Deliverables:
To complete this assignment you must --
Motivation: How do we use lots of variables? var x = 5, y = 10, z = 15; var sum = 0; sum = sum + x; sum = sum + y; sum = sum + z;Let's extend this to an arbitrary number, say 20, of variables with arrays. This would be tedious to input by hand with the method seen before. var size = 20; // Declare the array of 20 numbers var numbers[size];An array contains lots of variables, in this case, 20.
numbers[0] = 5;This gets the 0th variable in the array (the first one) and assigns it to 5, just like we set x = 5 earlier. Setting the rest: numbers[1] = 10; numbers[2] = 15;What about the rest of the 20 variables? Let's assign them to random integers. As a review, a random decimal can be created with Math.random(), then scaled to some range, say 100 by multiplying: Math.random() * 100, then rounded to an integer with Math.round(): Math.round(Math.random() * 100). numbers[3] = Math.round(Math.random() * 100); numbers[4] = Math.round(Math.random() * 100); ... numbers[19] = Math.round(Math.random() * 100);It's still tedious to initialize 20 numbers, but it's easier to keep track of with our numbers array. Here's a very nice way of repeating code, the for loop, which has the general syntax:
for(initialize; condition; increment){
statement
}
Which gets performed in the following order:1: initialize 2: condition: if true, perform statement, otherwise skip statement and increment and continue executing like normal. 3: statement 4: increment, repeat from 2 var i, numbers[20]; for(i = 0; i < 20; i++) numbers[i] = Math.round(Math.random() * 100);Let's trace how this code is executed: 1. i and numbers declared in memory. 2. i = 0 3. Check if i < 20. (0 < 20 yes), do statement. 4. numbers[i (which is 0)] is set to a random integer from 0-100. 5. Syntax: i++ is the same as i += 1 is the same as i = i + 1, so i = 0 + 1 = 1. 6. Check if i < 20. (1 < 20, yes), do statement. 7. numbers[1] = random integer from 0 to 100. ... After examining the trace, we know this will create an array of 20 random 0-100 ranged integers. Review loops and arrays lecture notes for further explanation. Let's return to the original example with Problem 1: summing over a list of numbers. Algorithm: 1. Create an array called list of size 10. 2. Initialize all elements of the list to random integers between 0 and 100 using a for loop. 3. Sum each element in the list with a for loop. You will need a new variable, sum, to store your total. 4. Output the sum with document.write or alert.
Problem 2: Comparing numbers.
|