110-12a.10
COMP 110
Loop and array self-help exercises: Answers
1. Write a loop to display the integers 0 through 9 in ascending order.
for (var i=0; i<10; i++)
{ alert(i);}
2. Write a loop to display the integers 9 through 0 in descending order.
for (var i=9; i>=0; i--)
{ alert(i);}
3. Write a loop to sum the integers 0 through 100.
var sum = 0;
for (var i=0; i<=100; i++)
{ sum = sum + i;}
// At the end of the loop, sum contains the sum of 0+1+…100.
4. Write a loop (plus one additional line of code) to calculate the average of the integers 0 through 100.
var sum = 0;
for (var i=0; i<=100; i++)
{ sum = sum + i;}
var average = sum/101;
5. Write code to create an array called grades and put the numbers
0, 10, 20, 30, 40, 50, 60, 70, 80, 90 into the array.
Several ways to do this
// Option 1: put values in when array is defined.
var grades = new Array(0,10,20,30,40,50,60,70,80,90);
// Option 2: Put all elements into the array at once,
// but after the array has been defined.
var grades = new Array;
grades = [0,10,20,30,40,50,60,70,80,90];
// Option 3: use a loop.
var grades = new Array;
for (var i=0; i<10; i++)
{ grades [i] = i*10; }
6. Write code to put 10 random integers in the range 0…100 into an array.
var grades = new Array;
for (var i=0; i<10; i++)
{ grades[i] = Math.round(100*Math.random());}
Math.random() returns a number from 0 up to, but not including 1. When you multiply by 100, you get a number from 0…99.9999… Then rounding gives an integer 0…100.
The remaining exercises use the array of random integers created in exercise 6.
7. Display only those elements of the array that are even. Generalize your code to handle an array of any size.
for (var i=0; i<grades.length; i++)
{ if (grades[i]%2 == 0) // Test to see if even.
{ alert (grades[i]);}
}
8. Create another array containing only those array elements that are in the range 25…75.
var newGrades=new Array; // Will hold grades in 25…75
var newGradesIndex=0;
for (var i=0; i<grades.length; i++)
{ if (grades[i]>=25 & grades[i]<=75)
{ newGrades[newGradesIndex]=grades[i];
newGradesIndex++;
}
}
// newGrades now contains elements from grades whose values
// are in 25…75.
9. Find the sum of the numbers in the array.
var sum=0;
for (var i=0; i<grades.length; i++)
{ sum = sum + grades[i];}
10. Find the average of the numbers in the array.
var sum=0;
for (var i=0; i<grades.length; i++)
{ sum = sum + grades[i];}
var average = sum/grades.length;
11. Find the smallest number in the array.
// Find the smallest element in the array.
var minSoFar = grades[0];
for (var i=1; i<grades.length; i++)
{ if (grades[i] minSoFar)
{ minSoFar = grades[i];} // New smaller value.
}
// minSoFar contains the minimum value.
12. Find the index of the smallest number in the array.
// Find the index of the smallest element in the array.
var minIndexSoFar = 0;
for (var i=1; i<grades.length; i++)
{if (grades[i] grades[minIndexSoFar])
{ minIndexSoFar = i;} // New smaller value.
}
// minIndexSoFar contains the index of the minimum value.
13. Write a function that takes an array as its parameter and returns the index of the smallest element.
function minIndex(a)
{
// Return the index of the smallest element in
// the array a.
var minIndexSoFar = 0;
for (var i=1; i<a.length; i++)
{ if (a[i] < a[minIndexSoFar])
{ minIndexSoFar = i;} // New smaller value.
}
// minIndexSoFar contains the index of the minimum
// value.
return minIndexSoFar;
}
14. Write a function that takes an array and an index as its parameters and returns the index of the smallest element in the subarray starting at the specified index.
function minIndex(a,s)
{
// Return the index of the smallest element in
// the subarray a[s…a.length-1].
// Restriction: s must be an integer in the range
// 0…a.length-1.
var minIndexSoFar = s;
for (var i=s+1; i<a.length; i++)
{ if (a[i] < a[minIndexSoFar])
{ minIndexSoFar = i;} // New smaller value.
}
// minIndexSoFar contains the index of the minimum
// value in a[s…s.length-1].
return minIndexSoFar;
}
15. Write a function to swap two elements of an array. Parameters are the array and the indices of the two elements to be swapped.
function swap(a, i, j)
{
// Swap the ith and jth element of the array a.
// Restrictions: a must be an array;
// i and j must be integers in the
// range 0…a.length-1.
var temp = a[i];
a[i] = a[j];
a[j] = temp;
}
16. Use the functions from exercise 14 and 15 to implement a selection sort function. The parameter will be the array to be sorted.
function sort(a)
{
// Sort the array a in ascending order by selection sort.
// Restriction: a contains numbers only.
for (var i=0;i<a.length-1;i++)
{
// Swap the smallest in a[i…a.length-1] with a[i].
{swap(a, i, minIndex(a, i)); }
}
}
17. Given that JavaScript uses call by value (i.e. gives the function a copy of the parameter, not the parameter itself), why do your swap and sort functions work?
The array name is actually a reference to the array itself. JavaScript passes a copy of the reference to the function, but the array referenced by the original reference and by the copy are the same.
18. Write a function that takes an array as its parameter and returns a sorted version of that array. The original array is not altered.
// Returns a sorted copy of array a.
function sortedVersion(a)
{
// Make a copy of array a.
var copy = new Array;
for (var i=0; i<a.length; i++)
{ copy[i] = a[i]; }
// Sort the copy.
sort(copy);
// Return the sorted copy.
return copy;
}
19. Write a function to search an array looking for key. Return the position of the first occurrence of key, or, if key isn’t found, return -1.
// Search list. Return the location of the first occurrence
// of key in list. If key is not in the list, return -1.
function search(list, key)
{
for (var i=0;i<list.length;i++)
{
if (list[i] == key) // key found in position i
return i;
}
// If we survive to here, key wasn’t found.
return -1;
}
20. Write a function to search an array looking for key. Return an array containing all the locations where key was found.
// Search list. Return an array containing all locations
// in the array where key was found.
function searchAll(list, key)
{
var foundList = new Array; // Contains locations where
// key was found.
var foundCount=0; // Count of the number of
// occurrences of key found
// so far.
for (var i=0; i<list.length; i++)
{
if (list[i] == key)
{ foundList[foundCount] = i; // Add to found location
// to found list.
foundCount++;
}
}
// Return found array. The array will be empty if no
// occurrences of key were found.
return foundList;
}
21. What is the output displayed by each of the following code fragments?
for (var i=0; i<10; i++)
{
alert(i);
}
10 alerts with the values 0…9.
for (var i=10; i<10; i++)
{
alert(i);
}
Nothing. The loop condition fails immediately.
for (var i=10;i>=0; i--)
{
alert(i)
}
11 alerts with the values 10 down to 0.
for (var i=0;i<5; i++)
{
for (var j=0; j<3; j++)
{
alert(i +" "+ j);
}
}
15 alerts with the following values.
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
3 0
3 1
3 2
4 0
4 1
4 2
Remember, when one loop is inside another, the inner loop runs to completion for every step of the outer loop.
for (var i=0; i<5; i++)
{
for (var j=i; j<5; j++)
{
alert(i +" "+j);
}
}
15 alerts with the following values. Note that the inner loop starts at a different value each time.
0 0
0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4
22. What does this code do?
var count=0;
for (var half=0; half<=2; half++)
{ for (var qtr=0; qtr<=4; qtr++)
{ for (var dime=0; dime<=10; dime++)
{ for (var nick=0; nick<=20; nick++)
{ for (penny=0; penny<=100; penny++)
{ if (50*half + 25*qtr + 10*dime + 5*nick + penny == 100)
{ count++; }
}
}
}
}
}
alert(count);
It counts and displays the number of different way to make $1.00 using half dollars, quarters, dimes, nickels, and pennies. It tests 349,965 different combinations to find the 292 combinations that add up to exactly $1.00.
Assume you are given a function p(x) that takes a parameter x and returns true if x has property p, and false if x does not have property p. It doesn't matter what property p is. Assume that the function p works for any x.
23. Write a function allP(a) that takes the array a as its parameter and returns true if all of the elements of a have property p. It returns false if not all the elements of a have the property. If an array has zero elements, then allP(a) is true. (Think about why this is the case. For example, if you turned in no assignments in a course, would it be truthful to tell your parents, "Every assignment I turned in got an A."?)
// Do all of the elements of array a have property p?
function allP(a)
{
for (var i=0;i<a.length;i++)
if (!p(a[i])) return false; // Found an element that does
// not have property.
return true; // Survived the loop.
}
24. Write a function someP(a) that takes the array a as its parameter and returns true if some (one or more) of the elements of a have property p. It returns false if none of the elements of a have property p. What should someP(a) be if a has no elements?
// Do one or more of the elements of array a have property p?
function someP(a)
{
for (var i=0;i<a.length;i++)
if (p(a[i])) return true; // Found an element that has
// the property.
return false; // Made it through the loop without finding an
// element that has the property.
}
25. Write a function countP(a) that takes the array a as its parameter and returns the number of elements of a that have property p. What should be returned if the array has no elements?
// How many of the elements of array a have property p?
function countP(a)
{
var count=0;
for (var i=0;i<a.length;i++)
if (p(a[i])) count++; // Found an element that has
// the property.
return count;
}
26. Write a function subP(a) that takes the array a as its parameter and returns another array containing only those elements of a that have property p. What should allP(subP(a)) return? Will this work properly even if none of the elements of a have property p?
// Create and return an array containing only those elements of p
// that have property p.
function subP(a)
{
var res=new Array;
var resIndex=0;
for (var i=0;i<a.length;i++)
if (p(a[i])) // Found an element that has the property.
{ res[resIndex]=a[i]; // Add found element to result array.
resIndex++; // Update index.
}
return res;
}
27. Write a function that takes two arrays, a and b, as parameters and returns true if every element of a is also in b. Hint: use number 19.
// Is every element of array a also in array b?
function subarray(a,b)
{
for (var i=0; i<a.length; i++)
{ if (search(b, a[i]) == -1) // a[i] is not in b.
return false;
}
return true; // Survived the loop.
}