CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to:

Similar documents
Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

A340 Laboratory Session #5

CMPT 100 : INTRODUCTION TO

JavaScript: Tutorial 5

Lab 8 CSE 3,Fall 2017

Lesson 1: Writing Your First JavaScript

Working with JavaScript

(Refer Slide Time: 01:40)

ORB Education Quality Teaching Resources

CSS worksheet. JMC 105 Drake University

Enhancing Web Pages with JavaScript

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

HTML/CSS Lesson Plans

1 Getting started with Processing

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Programming Lab 1 (JS Hwk 3) Due Thursday, April 28

Lab # 2. For today s lab:

UNIT 3 SECTION 1 Answer the following questions Q.1: What is an editor? editor editor Q.2: What do you understand by a web browser?

Functions, Randomness and Libraries

Shorthand for values: variables

Project 2: After Image

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CS Multimedia and Communications REMEMBER TO BRING YOUR MEMORY STICK TO EVERY LAB!

Lesson 1 HTML Basics. The Creative Computer Lab. creativecomputerlab.com

Variables and Typing

Intro. Scheme Basics. scm> 5 5. scm>

Beginning HTML. The Nuts and Bolts of building Web pages.

introjs.notebook March 02, 2014

CSCU9B2 Practical 1: Introduction to HTML 5

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Introduction to Programming with JES

COMS 469: Interactive Media II

EVENT-DRIVEN PROGRAMMING

Section 1. How to use Brackets to develop JavaScript applications

Looking at the Internet with Google Chrome & Firefox. Scoville Memorial Library Claudia Cayne - September, 2010

EXERCISE: Introduction to client side JavaScript

Problem 1: Textbook Questions [4 marks]

Princess Nourah bint Abdulrahman University. Computer Sciences Department

var num1 = prompt("enter a number between 1 and 12","1"); var promptstring = "What is " + num1 + " times 3?"; var num2 = prompt(promptstring);

ORB Education Quality Teaching Resources

Controlled Assessment Task. Question 1 - Describe how this HTML code produces the form displayed in the browser.

JS Lab 1: (Due Thurs, April 27)

BEGINNER PHP Table of Contents

JavaScript Introduction

Copyright 2018 MakeUseOf. All Rights Reserved.

Class 3 Page 1. Using DW tools to learn CSS. Intro to Web Design using Dreamweaver (VBUS 010) Instructor: Robert Lee

c122mar413.notebook March 06, 2013

Website Development Komodo Editor and HTML Intro

CS Problem Solving and Object-Oriented Programming

Initial Coding Guidelines

BEFORE CLASS. If you haven t already installed the Firebug extension for Firefox, download it now from

Unit 5 Web Publishing Systems Page 1 of 13 Part 4 HTML Part 4

Programming language components

Lesson 5: Introduction to Events

EXCEL BASICS: MICROSOFT OFFICE 2010

Lesson 6: Introduction to Functions

Manju Muralidharan Priya. CS4PM Web Aesthetics and Development WEEK 11

JavaScript Basics. The Big Picture

ASCII Art. Introduction: Python

EXCEL BASICS: MICROSOFT OFFICE 2007

CS1046 Lab 1. <h1> </h1> <h6>this is a level h6 header. Pretty small!</h6> Objectives: By the end of this lab you should be able to:

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Teach Yourself HTML5 & CSS 3: Week 5 Task 13 - Anchors Part 3

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

[ the academy_of_code] Senior Beginners

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

<script> function yourfirstfunc() { alert("hello World!") } </script>

Computer and Programming: Lab 1

CISC 110 Week 3. Expressions, Statements, Programming Style, and Test Review

Using Dreamweaver CS6

GoLive will first ask you if your new site will be for one individual or a work group; select for a Single User, and click Next.

JQuery and Javascript

Task 1. Set up Coursework/Examination Weights

Survey of Math: Excel Spreadsheet Guide (for Excel 2016) Page 1 of 9

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

6.170 Laboratory in Software Engineering Java Style Guide. Overview. Descriptive names. Consistent indentation and spacing. Page 1 of 5.

Chapter 17. Fundamental Concepts Expressed in JavaScript

Guidelines for doing the short exercises

Mobile App:IT. Methods & Classes

Anatomy of a Function. Pick a Name. Parameters. Definition. Chapter 20: Thinking Big: Programming Functions

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Session 3: JavaScript - Structured Programming

Dreamweaver: Web Forms

Animations involving numbers

Make a Website. A complex guide to building a website through continuing the fundamentals of HTML & CSS. Created by Michael Parekh 1

Math Day 2 Programming: How to make computers do math for you

HTML 5 and CSS 3, Illustrated Complete. Unit L: Programming Web Pages with JavaScript

TUTORIAL FOR IMPORTING OTTAWA FIRE HYDRANT PARKING VIOLATION DATA INTO MYSQL

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

CSC Web Programming. Introduction to JavaScript

JavaScript CS 4640 Programming Languages for Web Applications

COMP 110 Project 1 Programming Project Warm-Up Exercise

Unit Notes. ICAWEB411A Produce basic client-side script for dynamic web pages Topic 1 Introduction to JavaScript

What is Java Script? Writing to The HTML Document. What Can JavaScript do? CMPT 165: Java Script

Installing VS Code. Instructions for the Window OS.

Adobe Flash CS3 Reference Flash CS3 Application Window

Access Forms Masterclass 5 Create Dynamic Titles for Your Forms

CISC 1600 Lecture 2.4 Introduction to JavaScript

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can.

Tutorial 2 Editor Brackets

Transcription:

CS1046 Lab 4 Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to: Define the terms: function, calling and user-defined function and predefined function Call/use a predefined function Identify the parts of a function body, name, parameters, return value Trace a given user-defined function to determine what it will do/return Write/create/declare a user-defined function Call a user-defined function Determine the scope of a variable Use the predefined function Random to return a random number between two given values. Exercise 1 Some basic concepts: Functions, user-defined and predefined When baking a pie, we can divide our process into 4 steps: 1. Make the crust 2. Make the filling 3. Fill the crust with the filling and put the top on the pie 4. Bake the pie What we are doing is called Divide and Conquer. We are breaking a really big task (making a pie), into smaller, easier-to-accomplish tasks. Programmers do the same thing, they break a large program into small tasks (programmers call the tasks functions) and then put those functions together to create a working program. Now imagine that rather than having to make a fresh crust each time for pie, instead, you make it ahead of time and put it in the freeze for everyone who bakes to use (when they need some crust, they just pull some out of the freeze). Programmers do this also. One programmer will make a function (called a predefined function) that does some sort of task (like change the background colour of an object, that could be a predefined task) and share it with other programmers so that they don t have to waste their time writing the code again, they can just use the predefined function. Also when programming, there are tasks that a programmer knows will be needed to be done over and over again, such as writing to the webpage or getting the current date and time. Why should we force the programmer to write the statements for these actions over and over again when we could just write the required group of statements once and assign that group of statements a name, then we would call that name whenever we needed to perform the action. This is what a function is: a named group of statements or actions. For example, writing to the webpage, consists of a group of statements stored as 1

a function called write(). Thus, write(), is a function. Behind the scenes it is made up of many statements, but all we have to do when we want to write to the document is call the function write() as follows: document.write( hello world ); Calling a function means making the function perform (do something). In previous labs, you have used a few JavaScript functions such as getelementbyid(). In this lab, we will delve deeper into the use of functions. 1. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab4/lab4ex1a.html Right click and view the source for this page. 2. Create a new folder called lab4. Open Notepad and then save the file (in the lab4 folder) as yourwesternuseridlab4ex1a.html (eg. jsmith2lab4ex1a.html). It is important to save the file as an.html and not.txt file. Consult Lab 1 Exercise 5 if you have trouble. 3. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab4/lab4ex1.css and copy the stylesheet. Do this by using Notepad to create a new file in your lab4 folder, paste the css code in it and give this new file the name: lab4ex1.css 4. View the source for the.html file and find the tags that create the button. We are going to call the write function when the user clicks on the button by changing the <button> tag to this: <button onclick="document.write('hello World');" > Notice that the string, Hello World, is surrounded by single quotes. This is very important because we have already used the double quotes around the function call document.write(..); and if we were to use double quotes again the interpreter get mixed up, it won t know how to pair up the double quotes. That is why, in this case, you have to put the single quotes inside the double quotes. This helps the interpreter figure out the pairing. 5. Reload your webpage and click on the button and make sure that it writes Hello World to the page. You have just called a function. Congratulations. Now let us try calling some other functions now. Change: <button onclick="document.write('hello World');" > to <button onclick="alert ('Hello World');" > and reload your page and observe what the alert function does. 6. Now try using the open function (it opens a new tab in your browser window) as follows: <button onclick="window.open('http://www.csd.uwo.ca');" > 2

7. Reload the webpage and see what happens. JavaScript has a lot of ready-made (ready-to-use) functions that can perform a variety of tasks such as the three examples we have used so far write(), alert() and open(). These functions were each already set up to execute a specific task, and because of this, they are each what we call a predefined function. This means that some other programmer has created them for other programmers to use. When you use a predefined function it has two main parts depicted below: The function name, in this case: alert The function s parameters, in this case: one string, enclosed by quotes: Hello World alert( Hello World ); Just like humans are called by their name, a function is also called by its name. It is then always followed by an opening parenthesis and then sometimes by parameter(s) and then by a closing parenthesis. Parameters are extra pieces of information that you can pass into the function. Some functions need parameters, while others do not. Some functions may need more than 1 parameter, in that case, you separate the parameters by commas. For example, you might have a function called listcolors, and the call could be like this: listcolors( red, green, blue ); Sometimes the parameters are strings, like above, sometimes they are numbers, so you could have a function called addthemup and you could call this function like this: addthemup(45,67); 8. There are some functions that belong to objects and to call them we use a. (dot). For example, the write() function is a method/function of the document object. The open() function is a method/function of the window object. However, the alert() function doesn t belong to an object so we can just call it without a. (dot) in front of it. 9. In certain situations, it may be necessary to design our own functions because we cannot find a function that does exactly what we want. When we make up our own function, we have to first build it before we call it. This is similar to declaring variables before we use them. Every userdefined function must have a declaration. Here is the declaration for a sample user-defined function: function listcolors(col1, col2, col3) { document.write( <h2> My Favourite Colors</h2> ): document.write( <ul> ); document.write( <li> + col1 + </li> ); document.write( <li> + col2 + </li> ); document.write( <li> + col3+ </li> ); document.write( </ul> ); 3

Notice that when you design your own functions, you need to list the parameters as variables (the formal parameters). When you call your function, you will put values that will be passed into the parameter variables (the actual parameters). Thus, if the first line when we design our function is: function listcolors(col1,col2, col3) { Notice that col1, col2 and col3 are variables (3 formal parameters). When we call our function as follows: listcolors( blue, green, purple ); (here blue, green and purple are the 3 actual parameters) The values go into the corresponding variables, thus blue gets stored in col1, green gets stored in col2 and purple gets stored in col3. An alternative way to do this would be: var x, y, z; x= blue ; y= green ; z= purple ; listcolors(x,y,z); (here x, y and z are the 3 actual parameters) 10. Let s try building our own user-defined function. In Notepad, open a new file called functionbuilding.js (make sure it is in your lab4 folder) 11. In this new file, insert the following code: function listcolors(col1, col2, col3) { document.write("<h2> My Favourite Colors</h2>"); document.write("<ul>"); document.write("<li>" + col1 + "</li>"); document.write("<li>" + col2 + "</li>"); document.write("<li>" + col3+ "</li>"); document.write("</ul>"); 12. Save the.js file and go to your.html file and insert the following line just above the </head> tag: <script src="functionbuilding.js"></script> 13. Then change the <button> tag so that instead of calling window.open( ), it calls this function you just built whenever the button is clicked. Notice that the above function needs 3 actual parameters to go into the 3 formal parameters that are variables: col1, col2, and col3. So your function call should include your 3 favourite colours, for example: listcolors( Red, Orange, Yellow ); 14. Save your.html file and reload it and make sure it works. If it is not functioning properly, remember you can check the syntax of your code in Google Chrome by showing the Java Console (ctrl-shift-j), then click on the Sources tab, then click on your.js file. Make sure there are no syntax errors. 4

15. Let s review the parts of a function when creating (defining) a user-defined function: The function name, in this case: listcolors The opening and closing parentheses that indicate the start and end of the required parameters function listcolors(col1, col2, col3) { document.write("<h2> My Favourite Colors</h2>"); document.write("<ul>"); document.write("<li>" + col1 + "</li>"); document.write("<li>" + col2 + "</li>"); document.write("<li>" + col3+ "</li>"); document.write("</ul>"); The parameter list, variables, separated by commas The opening and closing curly brackets that indicate the start and end of the body of the statements to be performed by the function Congratulations, you now can: The body of the function, i.e the statements that make it do the require task Define the terms: predefined function, user-defined function Identify the following parts of a function: its name and its parameters Call one of the following predefined functions write(), alert() and open(); Create a user-defined function Call a user-defined function 5

Exercise 2 Practice writing functions, passing parameters and calling functions 1. We are going to write some functions that calculate the area and perimeter for a rectangle. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab4/lab4ex2a.html Right click and view the source for this page, copy the source into the lab4 folder with the name yourwesternuseridlab4ex2a.html (eg. jsmith2lab4ex2a.html). 2. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab4/lab4ex2.css and copy that code into your lab4 folder, using Notepad to create a new file, paste the css code in and give this new file the name: lab4ex2.css 3. View the source for your HTML file. Change the <h1> element at the top so that instead of saying Calculations Galore, it says YourFirstName s Calculations Galore (e.g. Homer s Calculations Galore) 4. Change the <button> tag so that it calls the function "alert('hello world');" when the user clicks on the button 5. Reload the HTML page and make sure that when you click on the button, it pops up the alert "hello world". 6. Now, in Notepad, open a new file and save it to your lab4 folder as shapecalculations.js 7. In your.html file add the <script> tags just above the </head> tag and make sure that it points to the script file called shapecalculations.js 8. In this file we will create a function that calculates the area of a rectangle, given its width and height. Notice that we have to give this function variables (this is called passing the variables) that hold the width and height, thus width and height will be the two formal parameters. We will call the function calcarea, thus the first line of your function should be: function calcarea (width, height) { type this into your new file (shapecalculations.js) 9. Next, we will declare (i.e., create) a temporary variable to hold the area. You should always indent functions a little bit, so now our function will look like this: function calcarea (width, height) { var area; 10. Next, we will calculate the area and store the value in the variable (again remember to indent your code within the function). Now you should have: function calcarea(width, height) { var area; area = width * height; Notice that the variable area is declared INSIDE the function. This means that only this function can use the variable area. It is called a local variable. We say it only has scope within the function, this means we can only give it a value or access its value in between the curly braces that indicate the start and end of this function. Another type of variable, a global variable, can be used outside or inside of this function, but not local variables. We will discuss global and local variables later. 6

11. When you write a function and you expect it to provide a final answer, the answer/response is called the return value. So now we are going to return back our answer from the function to wherever it was called from. This is called returning the value. Now your function will look like this: function calcarea(width, height) { var area; area = width * height; return area; 12. The last thing we need to do when declaring this function is indicate the end of the function with a closing curly brace. Thus our whole function looks like this: function calcarea(width, height) { var area; area = width * height; return area; 13. Save your.js file. 14. Now we need to make sure our new function, calcarea, works properly. To do so, we will test it in the HTML file by calling it. In the HTML function, change the <button> tag so that it says: <button onclick="alert(calcarea(2,3));"> and reload your page and click on the button. Remember to check the JavaScript console if it does not work (In Chrome, click on the setting button: > More Tools>Developers Tools) and see if you can identify errors that exist. 15. When you clicked on the button, it should have popped up the answer 6, this is because we passed into the function the width of 2 and height of 3(as parameters) calcarea(2,3). However, what we really want to pass into the function are the values that are typed into the text boxes. Let s change the HTML button tag to this : <button onclick="alert(calcarea(shapewidth.value,shapeheight.value));"> 16. Save the HTML file, type numbers in the textboxes and observe the changes when you click the button. 17. To beautify our webpage we could put our answer somewhere other than in a popup box. So right under the </button></p> tags in the HTML, add the line: <p>the answer is: <label id="answer"></label></p> Notice we gave used a <label> tag (<label> html tags just display a result) and we gave it the id of answer. This is where we are going to display the results on our page by referring to the element with the id of answer in the next steps. 7

18. Save your HTML file. Reload the page and make sure the answer paragraph is there. Now we have a little label called answer where we can display our answer. But now we need to change our function so that rather than returning the area to the alert popup box, it will instead put the area in the paragraph section. We will use the predefined function: getelementbyid to return that paragraph element and store that element in a variable, then we will assign the area answer to that variable. Go back into your.js file and change the function so that it now looks like this (new lines are red and remove the return line): function calcarea(width, height) { var area; var answerarea; area = width * height; answerarea=document.getelementbyid("answer"); answerarea.innerhtml=area; The innerhtml property sets everything in-between the tags for the answerarea to whatever value you give it. In this case we are giving it the area value we just calculated. Save your.js file 19. Go back to your HTML file and make one more change. We no longer need to call the alert function to display our answer, the way we have rewritten our code, it should just show up in the answer area. So change the <button> label as follows: <button onclick="calcarea(shapewidth.value,shapeheight.value);"> 20. Save the HTML file, reload the page and make sure it works. 21. Now create another button to calculate the perimeter of a rectangle. Put it right under the first Calculate Area button. Your HTML code should look like this (new line is red): <p><button onclick="calcarea(shapewidth.value,shapeheight.value);">calculate Area</button></p> <p><button>calculate Perimeter</button></p> 22. Now go back to your.js file and underneath the calcarea function (AFTER the closing curly brace), create another function called calcperi. This function should calculate the perimeter of a rectangle given its width and height (make them parameters again). NOTE: if you use the formula: peri = width+width+height+height; rather than the formula: peri=(1*width)+(1*width)+(1*height)+(1*height); you will get an unexpected result. See if you can figure out what it is doing. (Hint: thinks of Strings vs Numbers, multiplying a string by a number such as 1 is a little trick to turn it into a number.). Also, display the answer (peri) in the answer area you created. 23. Go back to your HTML file and change the onclick for the second button so that it calls the calcperi function. Make sure the perimeter is be displayed in the same answer paragraph location where you displayed the area of the rectangle. Make sure your code works by saving and refreshing and rerunning your code. 8

Just in case you are having problems (BUT TRY IT YOURSELF BEFORE LOOKING AT THE CODE IN BOX BELOW), your code should look similar to this: //calculate the area of a rectangle given its width and height function calcarea(width, height) { var area; var answerarea; area = width * height; answerarea=document.getelementbyid("answer"); answerarea.innerhtml=area; //calculate the perimeter of a rectangle given its width and height function calcperi(width, height) { var peri; var answerarea; peri = (width *2) + (height*2); answerarea=document.getelementbyid("answer"); answerarea.innerhtml=peri; Congratulations, you now can: Define the terms: local variable, return value Call the function/method getelementbyid() to retrieve a webpage element Pass values from textboxes into a function as parameters Write/declare a user-defined function Call a user-defined function Use the JavaScript Console in the browser to find mistakes (debug your code) Force a string into a number 9

Exercise 3 Generating Random Numbers 1. There are many times when writing computer programs that we will need a random number. For example, if you were going to have a Guess a number game, you could say to your user Pick a number between 1 and 10 and then in your code you might have: var answer; answer = 7; The first time the user plays the game he/she might not guess 7 but after playing your game just once, the user would already know the number. Therefore, it would be better if you changed the number each time the game is played. In JavaScript, it would be better if you could instead, do something like this: var answer; answer = randomnumber(1, 10); Card games on computers, like FreeCell and Solitaire, generate random cards so that it looks like the deck was shuffled, for example, the programmer might have something like: var suit; var number; suit = randomnumber(1,4); //picks a number from 1 to 4 where 1=clubs, 2=spades, etc.. number = randomnumber(1,13); //picks number from 1 to 13, where 10=10, 11=Jack, etc. Thus, if suit was 1 and number was 12, the card shown would be the Queen of Clubs. Every programming language has a predefined random number generating function. In this exercise, we will learn how to use JavaScript s random number generating predefined function. (It doesn t look exactly like the code written above, that was just to illustrate the point). 2. Using the Chrome browser, go to this webpage: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab4/lab4ex3a.html Right click and view the source for this page, save the source into the lab4 folder with the name yourwesternuseridlab4ex3a.html (eg. jsmith2lab4ex3a.html). 3. Look at the HTML tags and notice the <script> tag refers to the file called randomnumbers.js. Open a new file in Notepad and save it as randomnumbers.js in your lab4 folder. In randomnumbers.js declare a function called getrandomnumber. This function should have 2 parameters: low and high. At this point, it should look like this: function getrandomnumber(low, high) { 4. Next, we will add code between the curly brackets to get the random number. Let us try using the JavaScript random number generator Math.random() to see what it returns. Update your function so that it looks like this: function getrandomnumber(low, high) { var rannum; rannum = Math.random(); alert(rannum); 10

5. Notice that Math.random() is a predefined function that has NO parameters. Remember that some functions have no parameters. This function generates a real number from 0, up to but not including 1. Therefore, we might get the number 0.99999999999, or we might get the number 0.524, or we might get the number 0. 6. Save your.js file then return to your.html file, and change the <button> so that your getrandomnumber function is called when the user clicks on the button. At this point our low variable and high variable are just place holders with no functionality so you can set them to any value. Your HTML might look like this: <button onclick="getrandomnumber(1,10);"> 7. Save your HTML file and reload the page, click on the button a few times and notice that the number that appears is between 0 and 1. This real number has lots of decimals which makes it confusing. To change this real number to an integer we are going to use another Math function, Math.floor(). This function truncates your number to an integer, so if you put Math.floor(3.8887777), it would return 3. Our problem is that our number is always 0.????, so if we used Math.floor(Math.random()), we would always get 0. To get around this issue we will multiply Math.random() by 10, which will give us a real number between 0 and 9, next we will apply Math.floor to the result to make it an integer between 0 and 9 and finally we will add 1 to that number so that our final value is between 1 and 10. So, in your.js file, change the line rannum=math.random(); to rannum=math.random()*10 ; //generates a random number between 0.000 1 and 9.9999 9 rannum = Math.floor (rannum); //turn real number into an integer by dropping the decimals rannum=rannum + 1; //make the random number go from 1 to 10 rather than 0 to 9 8. Save your.js file and try pressing your button again a few times to make sure you are getting random numbers between 1 and 10. 9. Now we need to change the code so that it generates a random number between our low value and our high value (e.g. if low was 3 and high was 5, then we would want one of the numbers 3 or 4 or 5 (thus, we want THREE random numbers which is 5-3 PLUS 1, so we want high-low +1)). First, change your variables from strings to numbers and then update the rannum assignment statement so it uses our values as show below. low=low*1; //change from string to number high=high*1;//change from string to number rannum= Math.random()*(high-low+1); //figure out how many numbers to get Function should look like this now: 11

10. Save your.js file and then go to your HTML file and change the parameters that you are passing to the function call to be the textbox values like in the previous exercise. Notice that the ids are different for the low and high values from the previous exercise. 11. Save your HTML file and make sure it works. Press the button a few times. Notice that we are getting real numbers again not integers, remember we need to use Math.floor() to make it an integer, so now add this line in your.js file BEFORE the alert line: rannum=math.floor(rannum); //turn into integer 12. Save your.js file and test your code again. Notice we are not quite there yet. Now it generates random integers but it doesn t start at our lower boundary. We need to add the lower boundary to move it from starting at 0 to starting at that boundary. Go back to your.js file and add this line before the alert line rannum=rannum + low; //move the lower boundary up from 0 to the smallest number Your code should now look like this: 13. Save your.js file and test your html code again (reload it and press the button). Press the button a few times to make sure you are getting the correct numbers (E.g. try putting the boundaries as 3 and 5 and make sure you just get the numbers 3 OR 4 OR 5, then put the boundaries as 8 and 11 and make sure you get 8 or 9 or 10 or 11 ). 14. Now change your code so that it displays on the page (below the button) rather than popping up in the alert window. Congratulations, you now can: Use Math.random() to get a random value. Use Math.floor() to change a real number to an integer, to truncate the real number. Perform multi-step mathematics. 12

Exercise 4 Testing local variables and global variables and scope rules 1. This time you are just going to watch what happens with variables, so you don t need to copy this file to your lab4 folder, you can just open it here: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab4/lab4ex4a.html 2. Then open the file: http://www.csd.uwo.ca/~lreid/cs1046/labs/lab4/scopingrules.js and look at the alerts, which are OUTSIDE of the functions. Look at the global variables at the top. We can use them anywhere, but the local variables that are declared in the functions can only be used in their associated function. 3. Click on the buttons, then look at the values on the bottom of the page and try to figure out what will be in each of the variables. Trace them on paper (draw a box for each variable and show what is in each variable). Walk step by step through each line for each function, trying to determine how each variable will change. Scoping, global variables and local variables are some of the hardest concepts for new programmers to master. If you don t quite understand this code, see your instructor to review this with you. Congratulations, you now can: a. Determine when a local variable will lose its scope b. Trace a function that uses global and local variables HAND THIS WORK INTO OWL IN ORDER TO GET YOUR LAB MARK. 1. Go into owl and for Lab 4, submit the file called yourwesternuseridlab4ex2a.html AND shapecalculations.js so that we can check that your code is working properly. 13