Functions and Arrays Programs NOTE. Do not use any global variables unless explicitly told to do so. AP CSP Exercise 1. Create a program that calculates the distance between a point and the origin. Since we are practicing writing functions that return a value, you must write a function named distance that, given the coordinates of a point, returns the distance from that point to the origin. onevent("btndistance", "click", function(event) { var x = getnumber("txtx"); var y = getnumber("txty"); var dist = distance( x, y ); settext( "lbldistance", "This point is " + dist + " units from the origin"); To take the square root of a number, use the Math.sqrt function. For example: var num = Math.sqrt( 25 ); // num equals 5 Exercise 2. Let s review some geometry. A simple parabola, with its axis of symmetry parallel to the y-axis can be represented by the following equation: y = Ax 2 + Bx + C where A 0 y axis of symmetry This is the equation of a vertical line that defines the parabola's axis of symmetry. The vertex of the parabola is the point where the axis of symmetry intersects the parabola. So, we know the x-coordinate of the vertex and we use that value to find the y-coordinate from the equation of the parabola. You must use the following outline though you need not use my element names/ids. onevent("btnparabola", "click", function(event) { var a = getnumber("txta"); var b = getnumber("txtb"); var c = getnumber("txtc"); var x = axis( a, b ); var y = findy( x, a, b, c ); Display the results in one or two labels. Notice that you must write two functions for this program. vertex x 1
The % operator finds the remainder of a division operation. It is sometimes called the mod (short for modulo) operator which is correct for positive values. I will only use % with positive integer values. var a = 18 % 10; console.log( a ); // displays 8 var b = 30 % 6; console.log( b ); // displays 0 var c = 4 % 5; console.log( c ); // displays 4 Exercise 3. Complete the program so it works as shown in the two examples to the right. The isfactor function uses the % operator and returns true or false as appropriate. onevent("btncheck", "click", function(event) { var g = getnumber("txtg"); var h = getnumber("txth"); if ( isfactor( g, h ) ){ settext("lblfactor", "Yes"); else { settext("lblfactor", "No"); Exercise 4. When the button is clicked, the prices of 2 to 20 pretzels appears in the Text Area element below the button. You must write a function that returns the cost of x pretzels. The function will have three parameters: the cost of one pretzel, the cost of three pretzels, and the number of pretzels being purchased. This function will need to use the % operator. It should be about 3 lines long and contain no if statements or loops. Instead of displaying the results in a label, display them in a Text Area element (make it read-only). This kind of element will automatically add vertical scroll bars if needed. 2
Exercise 5. A quadratic equation is one that can be written in the following form. y = Ax 2 + Bx + C where A 0 And yes, it is also the equation of a parabola. The roots of this equation are the values of x when y equals zero. One approach to find the roots is to use the quadratic formula. The term under the radical, b 2-4ac, is called the discriminant. If the discriminant is positive, there are two roots. If it is zero, there is one root. If it is negative, there are no real roots. Now that I've refreshed your memory, let's get started on the program. These figures show results for three different sets of inputs. Your program should include a function that has three parameters (a, b, c) and returns the discriminant. Exercise 6. There is one global variable, an array. The user adds items to the array by entering the word and clicking the Append button. Items can be removed by entering their index and clicking the Remove button. The Text Area element below the buttons is updated to show the contents of the array whenever the contents change. The figure on the left shows what the program should like when it first starts. The middle figure shows the program after three items have been added. The figure on the right shows the program after the item at index 0 (cat) was removed, and the other items shifted their indices. Please follow the outline on the next page. 3
var a = []; onevent(, "click", function(event) { // the append button Add whatever they entered to the end of the array displayarray(); settext(" ", "" ); // clear the text in the box next to the Append button onevent("btnremove", "click", function(event) { Delete the item at the selected index displayarray(); settext(" ", "" ); // clear the text in the box next to the Remove button function displayarray(){ Display the contents of the array, with their indices, as shown previously. Exercise 7. There are two buttons, two labels, and one text box. The top figure shows the program when it first starts. When the top button is clicked, an array is displayed in the label below the top button. The user then enters a number in the text box and clicks the bottom button which counts the number of times that number appears in the array. The user can generate new arrays and count var a2 = []; onevent(" top button ", "click", function(event) { a2 = initarray( 6, 10, 1, 4 ); settext("top label", a2 + "" ); settext("bottom label", "" ); function initarray( n1, n2, n3, n4 ){ var temp = []; Generate a random number [n1, n2] Append that many numbers to temp. Each item is a random number [n3, n4] return temp; onevent(" bottom button ", "click", function(event) { Count the number of times the target number appears in the array. Display the results in the label below the bottom button. 4
Exercise 8. There is one button and one label. When the button is clicked, a random array is generated and displayed. Below that the average of the numbers in the array is displayed along with the minimum and maximum values in the array. Every time the button is clicked, a different array is generated, and new results are displayed. Your program must follow this outline and write the three functions shown below. Notice that this program does not use any global variables. onevent(" button ", "click", function(event) { var ray = initarray( 6, 10, 0, 50 ); // initarray is a function you wrote for exercise 7 var avg = findaverage( ray ); var min = findmin( ray ); var max = findmax( ray ); Display the contents of the array followed by the average of the numbers and the min and max function findaverage( nums ){ Returns the average of all the numbers in the array. function findmin( nums ){ Returns the minimum value in the array function findmax( nums ){ Returns the maximum value in the array The flowchart to the right shows an algorithm for finding the minimum value in an array. This can be adapted to find the maximum value in the array. min = array[ 0 ] i = 1 i < array.length true array[i] < min false i++ false true min = array[ i ] 5
Exercise 9. In this program there are two buttons and two labels. The user enters a name every time the top button is clicked. The name is entered into an array and the updated array is displayed in the label between the buttons. The person may enter as many names as they want. When the bottom button is clicked, a random person is removed from the array and displayed in the bottom label. Every time the bottom button is clicked, another person is randomly selected. If the bottom button is clicked when the array is empty, display an appropriate message. This is what the program looks like after adding three names. The Next button was clicked; Mary was randomly selected and removed from the array. This is the program after every one has been selected and the Next button was clicked again. Suggestions. Create a global variable that starts as an empty array Use the prompt function (in the Variables section of the toolbox) to get each name. When the bottom button is clicked, first check the length of the array. If it s zero, then... Use randomnumber to select the index. Then copy the name at that index into a variable. Then remove that item from the array. Exercise 10. This program displays an array of images and animated gifs. Click a button to show each one in turn. There are three image elements on the screen; one holds the picture/gif to be displayed, the other two are the buttons to move back or forward through the array of images. Here s an outline: var images = []; // global variable images[0] = "https://... a school appropriate link..."; images[1] = " https://... a school appropriate link..."; at least three images/animated gifs var index = 0; setimageurl("id of main image", images[ index ] ); When the Back button is clicked, Reduce the variable index by 1 If index < 0, set it to the last valid index of the array Call setimageurl (as shown above) The code for the Forward button is similar to the code for the Back button. 6