The Open University, Walton Hall, Milton Keynes, MK7 6AA First published 2004

Size: px
Start display at page:

Download "The Open University, Walton Hall, Milton Keynes, MK7 6AA First published 2004"

Transcription

1 8 Programs ad data

2 This publicatio forms part of a Ope Uiversity course M150 Data, Computig ad Iformatio. Details of this ad other Ope Uiversity courses ca be obtaied from the Course Iformatio ad Advice Cetre, PO Box 724, The Ope Uiversity, Milto Keyes MK7 6ZS, Uited Kigdom: tel. +44 (0) , geeral-equiries@ope.ac.uk Alteratively, you may visit the Ope Uiversity website at where you ca lear more about the wide rage of courses ad packs offered at all levels by The Ope Uiversity. To purchase a selectio of Ope Uiversity course materials visit the webshop at or cotact Ope Uiversity Worldwide, Michael Youg Buildig, Walto Hall, Milto Keyes MK7 6AA, Uited Kigdom for a brochure. tel. +44 (0) ; fax +44 (0) ; ouweq@ope.ac.uk The Ope Uiversity, Walto Hall, Milto Keyes, MK7 6AA First published 2004 Copyright ª 2004 The Ope Uiversity All rights reserved. No part of this publicatio may be reproduced, stored i a retrieval system, trasmitted or utilized i ay form or by ay meas, electroic, mechaical, photocopyig, recordig or otherwise, without writte permissio from the publisher or a licece from the Copyright Licesig Agecy Ltd. Details of such liceces (for reprographic reproductio) may be obtaied from the Copyright Licesig Agecy Ltd of 90 Totteham Court Road, Lodo W1T 4LP. Edited, desiged ad typeset by The Ope Uiversity. Prited i the Uited Kigdom by The Alde Group, Oxford. ISBN B/m150b2u8i1.1

3 CONTENTS 1 2 Itroductio... 5 Arrays Structured data What is a array? 6 The JavaScript Array object Declaratio ad iitialisatio of arrays Accessig idividual array elemets Array legth Processig the elemets of a array usig a for loop 12 Outputtig all the elemets of a array 12 Plaig the steps i a programmig task 12 Carryig out trasformatios o each elemet 13 Summig the values i a umeric array 15 Eterig data values ito a array 18 Fidig the maximum value i a array 21 Improvig the iformatio i the output Usig parallel arrays Maagig the precisio of umeric output Summary 29 3 Fuctios Dealig with subtasks i programs Usig fuctios i JavaScript Writig fuctios i JavaScript Fuctios with argumets Fuctios which retur a value A fuctio to tidy up the umeric output Fuctios with more tha oe argumet Code reuse Hits for writig fuctios Summary 48 3

4 Uit 8 Programs ad data 4 Evets ad evet hadlers Graphical user iterfaces Evets Addig GUI compoets to programs 51 Addig a text box to the form Usig fuctios as evet hadlers Addig user iput to a GUI A uits coversio program Summary 66 5 Strigs Strig processig Some character-processig fuctios 68 Testig whether a character is a digit 69 Testig whether a character is alphabetic 70 Testig whether a character is alphaumeric A password-checkig program Summary 77 6 Uit summary Learig outcomes 78 Key terms 80 This uit was prepared for the course team by Staley Oldfield. 4

5 Itroductio 1 Itroductio I Uit 7 you were itroduced to the basic elemets of JavaScript; you leared to store, retrieve, ad maipulate simple data items such as umbers, strigs ad Boolea values, ad to carry out simple operatios o this data, usig the basic cotrol structures of sequece, repetitio ad selectio. I real life, data for ad from programs ofte comes i collectios which are related to each other i some way. I this uit, we move from the maipulatio of sigle-valued data to the use of a array as a simple example of a data structure. Such data structures allow us to hadle collectios of related data, e.g. raifall figures for each moth of a give year, as a sigle amed etity. We also look i more detail at how to maipulate idividual characters i strigs, which i may ways are similar to arrays. I real life, programs are ofte very large ad have may separate subtasks to perform. This uit starts to look at the ways i which we ca write separate pieces of code, kow as fuctios, to hadle each of these subtasks. You will see how these fuctios ca the be combied or reused, as ad whe required, to create a overall program to carry out a particular task. Fially, i real life people prefer to iteract with the computer through iterfaces which are easy to use ad easy to uderstad. This uit looks at simple ways of creatig programs which respod to user-geerated evets such as mouse clicks, ad at how JavaScript eables the programmer to provide graphical user iterface (GUI) elemets for data iput ad output. There are a lot of ew cocepts ad terms i this uit. However, most of the programmig activity that you will udertake o your ow requires you to make relatively mior modificatios to the code of programs that you have already looked at. I studyig the uit, you will eed to access files provided o the Block 2 CD-ROM, which you should already have istalled o your computer. You may also fid it useful to refer to the Block 2 Software Guide. While we do ot ited to tur you ito a computer programmer, we wat to show you some of the features of moder programmig laguages so that you ca appreciate the power of what ca be achieved usig them. Part of the art of programmig lies i recogisig that, although tasks are all differet, each ew task usually has features that you have met before, ad for which you have already successfully devised a solutio. Recogisig ad reusig patters i the structure ad the processig of data is at the heart of programmig. 5

6 Uit 8 Programs ad data 2 Arrays This sectio aims to: itroduce you to the array as a example of a data structure for hadlig collectios of related data; itroduce Array objects as the way i which JavaScript provides us with methods for maipulatig arrays of data; illustrate the use of arrays by writig code to implemet some of the stadard patters of activity associated with array data; emphasise the use of the for loop to carry out repetitive processes o data stored i arrays. 2.1 Structured data There are may situatios where we wat to deal with a collectio of data values that are related to each other i some way. For example, we may have data o the total raifall (recorded i millimetres) i our local area for each moth of a give year, or we might have the titles of all the tracks o our favourite CD. I processig such collectios of data values, we will ofte wat to treat each value i a collectio i a similar way, so we eed a mechaism for showig that they are related ad, equally importatly, how they are related. I such situatios we talk about structured data. 2.2 What is a array? Collectios of data values come i may differet patters. The patter that we are goig to look at more closely is a collectio cosistig of a list of data values that are all of the same type, e.g. all umeric values or all strig values, ad where the importat relatioship betwee the values is their relative positio i the list. What determies the positio i the raifall example is the relevat moth of the year, whereas i the CD example it is the particular track o which the amed piece of music is recorded. I most programmig laguages the ame give to such a data structure is a array, ad we talk about each data value as a elemet of the array. The positio of a elemet i the array is the give by a idex (sometimes referred to as a subscript). It is usually helpful to have a metal picture of a data structure to work with ad Figure 2.1 shows a 6

7 Arrays array of five elemets, each of which is a umber, with the associated idex values, ruig from 0 to 4. myarray idex values array elemets As with strigs, the idex values of arrays i JavaScript are umbered from 0 rather tha from 1. This feature is kow as zero-based idexig. Figure 2.1 myarray showig ame, idex ad elemets A array variable eeds a ame to idetify it, e.g. myarray i Figure 2.1. The way that JavaScript (ad most other programmig laguages) accesses the idividual elemets of a array is by usig square brackets, so that myarray [3] is the fourth elemet i the array ad has the value 7. SAQ 2.1 (a) What is the value of the elemet i the secod positio i the array i Figure 2.1? (b) What is the positio of the elemet i the array whose value is 2? What is its idex? Aswer to SAQ (a) The secod elemet is myarray [1] (remember that the first elemet is myarray [0]) ad has the value 5. (b) The value 2 is i the fifth positio, ad its idex is 4. The JavaScript Array object I JavaScript, array data structures are represeted ad maipulated usig the built-i Array object. This provides everythig you will eed i order to write programs which hadle array data ad more. Although JavaScript has a exceptioally large set of features for processig arrays you will be usig very few of them i M150, as our aim is simply to esure that you uderstad the basic otatio ad ideas eeded for stadard array maipulatio. 2.3 Declaratio ad iitialisatio of arrays I a JavaScript array, whe you kow the exact umber of elemets ad their values, e.g. whe there are 12 separate mothly raifall figures for a give year, the simplest way to declare the array is as follows. var raiarray = [111,115,200,95,23,59,68,33,39,144,66,37] We have give the array the variable ame raiarray ad have icluded the list of mothly raifall data values i millimetres (mm) as successive 7

8 Uit 8 Programs ad data raiarray Figure 2.2 raiarray declared with iitial values raiarray 0? 1? 2? 3? 4? 5? 6? 7? 8? 9? 10? 11? Figure 2.3 raiarray of size 12 declared with uiitialised elemets elemets, i a comma-separated list eclosed by square brackets. I fact, by providig a list of values, we have iitialised as well as declared our array. The JavaScript iterpreter recogises this as a array declaratio because the data is eclosed i square brackets. The first value represets Jauary raifall, the secod February, ad so o (though JavaScript has o way of kowig this!). Figure 2.2 shows the state of the array after this declaratio. If you kow the umber of elemets i a array, but expect the actual values to be provided later, durig the executio of the program, the you ca simply reserve memory for the array, as follows. var raiarray = ew Array(12) The JavaScript reserved word ew is used to create a ew Array object ad this statemet will set up the array ad provide eough memory for the 12 elemets that are to be stored i it. Sice we have ot yet provided ay values for the array elemets, they have the special default value of udefied, ad it would be wrog to try to retrieve or maipulate what is stored i these memory locatios before values have bee assiged to them. Figure 2.3 shows the array where questio marks deote the value udefied. All our array examples so far have cotaied umbers as elemets. As a fial example we cosider the declaratio of a array cotaiig strigs as elemets. As always, the strigs are eclosed i sigle quotes so that the iterpreter ca distiguish them from variable ames. var weekdayarray = ['Suday','Moday','Tuesday','Wedesday', 'Thursday','Friday','Saturday'] SAQ 2.2 (a) Write dow a JavaScript statemet to declare a array which could be used to hold the values of four TMA marks for a course. (b) The percetage marks gaied by a studet for the five TMAs o a previous course were 83, 79, 90, 81 ad 75. Write dow a JavaScript statemet to declare ad iitialise a array holdig these values, i the order give. (c) Write dow a JavaScript declaratio to create ad iitialise a array to hold the ames of the four seasos of the year. I all three cases you will eed to thik of suitable ames for the array variables. Aswer to SAQ (a) var mymarkarray = ew Array(4) (b) var previousmarkarray = [83,79,90,81,75] (c) var seasoarray = ['Sprig','Summer','Autum','Witer'] The ames of your arrays may differ from ours, but you should have chose ames that are meaigful i the cotext of the data they cotai. 8

9 Arrays 2.4 Accessig idividual array elemets Havig set up a array you eed to be able to iitialise or modify the values of its elemets ad to read i ad write out these values. You ca do this usig the square bracket otatio for arrays. For example, if you received a mark of 95 for the secod TMA of this course the you could record that i mym150markarray, usig the followig assigmet statemet. mym150markarray [1] = 95 To retrieve ad use the curret values of elemets already preset i our arrays you ca use statemets such as februaryrai = raiarray [1] ad previoustma01mark = previousmarkarray [0]. To write the curret value of a array elemet directly to the documet i the browser widow you ca write statemets like documet.write('my mark for TMA02 was ' + mym150markarray [1]) You will recall that we start coutig from 0 to determie the idex for the required elemet. mym150markarray mym150markarray[1] = Figure 2.4 mym150markarray showig the assigmet of a value to a array elemet SAQ 2.3 (a) Write a JavaScript statemet that assigs the July value from the array holdig the raifall data to a variable amed julyrai. (b) Write a JavaScript statemet that records a mark of 92 for the first TMA of your M150 course i mym150markarray. (c) How would you access the ame of the first day of the week from weekdayarray as declared i Subsectio 2.3? Aswer to SAQ (a) julyrai = raiarray [6] (b) mym150array [0] = 92 (c) The first day of the week could be accessed as weekdayarray [0] (which would have the value 'Suday'). 9

10 Uit 8 Programs ad data 2.5 Array legth As with the Strig objects discussed i Uit 7, JavaScript Array objects have a legth property, which idicates the umber of elemets i the array. To fid the legth of a array amed myarray, for example, we use myarray.legth. It is importat to remember that the legth of a array is oe greater tha the idex value of its last elemet so that, for example, weekdayarray.legth has the value 7, but the last day of the week is weekdayarray [6]. More geerally, the last elemet i a array called somearray ca be accessed as somearray [somearray.legth 1]. weekdayarray 0 'Suday' 1 'Moday' 2 'Tuesday' 3 'Wedesday' 4 'Thursday' 5 'Friday' 6 'Saturday' weekdayarray.legth is 7 weekdayarray[weekdayarray.legth 1] is 'Saturday' Figure 2.5 weekdayarray showig array legth, ad access to last elemet It is ow time to look at some simple code which uses the ew ideas itroduced so far i this sectio. ACTIVITY 2.1 Ope the file Program_8.2.1 i Notepad. Read through it carefully ad write dow the output that you would expect from ruig the program. The ru the program ad compare your expected output with the results displayed. If you do t get it right, have aother look at the program ad see if you ca work out why. Discussio 10 Here are some of the thigs you might have oticed. The legth of a array is ot affected by the fact that some of its elemets may ot have bee defied. For example, the empty array secodarray has legth 12, eve though oe of its elemets have bee defied. If a elemet i a array has ot bee defied, it will have a special value called udefied. The JavaScript iterpreter will also report the value of a o-existet elemet, outside the bouds of the array, as havig the special value udefied (e.g. tryig to access the sixth positio i firstarray). Whe displayig a elemet of a array usig documet write(), ay elemet which has the default value udefied will be coverted to the strig 'udefied' for display purposes. If documet.write() is used to display the

11 Arrays etire cotets of a array, ay udefied elemets are ot displayed. However, a comma is still displayed to separate each elemet whether or ot it is udefied. EXERCISE 2.1 The commets for each of the followig fragmets of JavaScript code specify what the code should do, but there is at least oe error i the code. Write dow the correct code i each case. (a) /* declares a array called myarray with 15 elemets */ var myarray = array(15); (b) /* write out the first elemet i the array myarray */ documet.write('first elemet is ' + myarray [1]) (c) /* write out the legth of the array myarray */ documet.write('legth of myarray is ' + myarray.size) (d) /* write out the last elemet i the array myarray */ documet.write('last elemet i myarray is ' + myarray [myarray.legth]) Discussio (a) /* declares a array called myarray with 15 elemets */ var myarray = ew Array [15]; There were three errors here: the keyword ew is eeded; JavaScript is case sesitive ad object types i JavaScript start with upper-case letters; square brackets are eeded to declare a array i this way. (b) /* write out the first elemet i the array myarray */ documet.write('first elemet is ' + myarray [0]) Remember array idexes i JavaScript are zero based. (c) /* write out the legth of the array myarray */ documet.write('legth of myarray is ' + myarray.legth) The Array property which gives the legth of a array is called legth ot size. (d) /* write out the last elemet i the array myarray */ documet.write('last elemet i myarray is ' + myarray [myarray.legth 1]) As array elemets are idexed from zero, the last elemet has a idex which is oe less tha the legth of the array. 11

12 Uit 8 Programs ad data 2.6 Processig the elemets of a array usig a for loop I Uit 7 you leared about the for loop cotrol structure for hadlig repeated actios whe you kow how may data items eed to be processed. We ofte wat to apply essetially the same operatio to every elemet of a array, such as eterig data values, trasformig data values or outputtig data values. By takig advatage of the legth property, a for loop ca be used to iterate through the elemets of a array. We ow look at some commo activities carried out o array data structures. You ca use the legth property to fid the umber of elemets i a array. Outputtig all the elemets of a array A commo requiremet is to produce a list of the values of the elemets i a array. You might wat to write out all the mothly raifall figures i the raifall array, startig from the elemet with idex 0 through to the elemet with idex 11, givig 12 elemets i all. Plaig the steps i a programmig task A algorithm is a clearly specified set of istructios to be followed i order to carry out a task or obtai a solutio to a problem. This geerally cosists of a umber of activities to be udertake, with appropriate sequece, selectio ad repetitio. It is useful to have a way of represetig the algorithm for a programmig task that is idepedet of the laguage i which the program will be writte. Oe approach is to use flowcharts, which are diagrams similar to those used i Uits 6 ad 7 to illustrate loopig ad coditioal structures. Aother, which we use here, is to write istructios i a restricted subset of Eglish, together with keywords similar to those foud i programmig laguages. The layout of the text also gives some visual idicatio of its structure. Istructios writte i this way are kow as structured Eglish. Structured Eglish is sometimes kow as pseudo code as its keywords ad layout resemble those of program code. We ca use structured Eglish to express the steps i writig out the raifall figures as follows. for each moth of the year write out the raifall figure for that moth ed for Note the use of the word for to idicate the eed for repetitio, the idetatio of the write statemet, ad the explicit closure of the loop by the words ed for. I order to traslate this ito a JavaScript for loop structure we eed to declare a variable, such as moth, as a loop couter; specify a startig value for moth, i this case 0 to start at the first elemet of the array; 12

13 Arrays formulate the coditio for iteratig roud the loop. Give that coutig starts at 0, this will be moth < raiarray.legth. fially, state the rule for icremetig the loop couter. Sice we wat every value to be output, moth = moth + 1. Puttig these together gives the followig JavaScript code. for (var moth = 0; moth < raiarray.legth; moth = moth + 1) documet.write(raiarray [moth] + '<BR>') The <BR> tag is eeded to produce a ew lie. ACTIVITY 2.2 The file Program_8.2.2 cotais the full workig code for outputtig the elemets of raiarray. Ope the file i Notepad ad read the code carefully. Look at the data values i the array, ad decide what you expect the output to be. The ru the program to check whether the actual output is what you expected. If it is ot, go back to the code ad try to fid out why. Discussio You should have foud this code quite straightforward, but it s always a good idea to ru code that you thik you uderstad, just to make sure that it behaves as you expect. We do ot look i ay detail at testig code i this uit but you met some ideas about testig i Uit 7, ad it will be discussed i more depth i Uit 10. Carryig out trasformatios o each elemet Suppose the raifall data is required i iches as well as i millimetres. The costat to covert millimetres to iches is , so each data value eeds to be multiplied by We ca use a for loop to carry out this activity, covertig each value i tur. A additioal Array variable, say ichraiarray, is eeded to store the coverted values. I structured Eglish we could write the task as follows. for each moth of the year set raifall i iches to raifall i mm * ad store it i the equivalet positio i ichraiarray ed for This ca be traslated directly ito JavaScript, as follows. for (var moth = 0; moth < raiarray.legth; moth = moth + 1) ichraiarray [moth] = raiarray [moth] * Figure 2.6 shows what happes. 13

14 Uit 8 Programs ad data raiarray ichraiarray * Figure 2.6 Mappig of values from raiarray to ichraiarray for equivalet moths EXERCISE 2.2 (a) Write a JavaScript declaratio for ichraiarray, the array which holds the coverted values. (b) Why might you wat to store the coverted values as well as the origials? (c) Write a JavaScript statemet to display the values i ichraiarray, each o a ew lie. Hit You may fid it helpful to look at the way the values i raiarray were displayed earlier i this subsectio. Discussio (a) var ichraiarray = ew Array(12) The ew array ichraiarray cotais exactly 12 elemets. More geerally, if you kew that you wated a array of the same legth as raiarray, but did t kow what that legth was, you could use the legth property as follows. var ichraiarray = ew Array(raiArray.legth) (b) Both sets of data might be eeded later i the program. For example, you might wat to prit out the two sets of values i colums, or do some further calculatios o the coverted values without havig to recalculate them. (c) for (var moth = 0; moth < ichraiarray.legth; moth = moth + 1) documet.write(ichraiarray [moth] + '<BR>') 14

15 Arrays Here we have reused the patter of code developed earlier i the subsectio to write out the values of the elemets i the ew array, just chagig the array s ame from raiarray to ichraiarray i that code. ACTIVITY 2.3 The file Program_8.2.3 cotais the code for covertig the data i raiarray from millimetres to iches, storig it i ichraiarray ad the displayig the cotets of the ew array. Ope the file i Notepad ad read the code carefully. Work out a few of the calculatios from millimetres to iches by had or calculator. The ru the program to see whether it produces the expected output. Discussio This program is a little more complex tha the oe you studied i Activity 2.2. Note i particular the declaratio of the array called ichraiarray ad the use of the loop cotrol variable, moth, to access the values at the same positio i both arrays. Oce a collectio of data values have bee etered ito a array, there are may ways that they could be processed, such as the followig. Carryig out a simple, idetical trasformatio o each elemet (e.g. as i the coversio of mm to iches). Trasformatio is the process of maipulatig oe piece of data so as to produce aother, e.g. performig a calculatio o a umber or chagig the characters i a strig, say from upper to lower case. Fidig the total value of all the umeric elemets i a array or idetifyig the largest or smallest elemet. Fidig out whether a particular value is curretly stored as a elemet of the array ad, if so, i what positio(s) i the array it is stored. Sortig the elemets i a array accordig to some rule, e.g. i icreasig order of size if the elemets are umeric or i alphabetical order if the elemets are text strigs. Some of the umbers may look a little odd, i.e. there may be more digits to the right-had side of the decimal poit tha you might have expected. This is caused by the way JavaScript traslates real umbers ito biary ad back. It is a commo computig problem to be aware of. We ow look at a few of these array processig activities. Summig the values i a umeric array Give the array of raifall values for each moth of the year, we may be iterested i kowig the aual raifall for the year. This ivolves addig up all the values that are stored i the array ad keepig track of the ruig total. You saw a similar example of fidig the total of a series of data values i Uit 7, though i that example the values were etered, oe at a time, by the user. You will recall that the variable used to store the total, which we will call aualraifall, eeds to be iitialised (to 0) before the process of addig ca be started. The value of each elemet of the array the eeds to be added to the total, aualraifall. As all the elemets of the array eed to be processed ad the array s size is kow, a for loop ca 15

16 Uit 8 Programs ad data hadle the repetitio ivolved. Fially, the value of aualraifall ca be displayed. A structured Eglish statemet of the activities that the program has to carry out, assumig that the data is already stored i the array, is give below. iitialise the raifall total to zero for each moth of the year add the raifall for that moth to the curret raifall total ed for write out the fial raifall total This ca be traslated directly ito JavaScript, as follows. aualraifall = 0; for (var moth = 0; moth < raiarray.legth; moth = moth + 1) aualraifall = aualraifall + raiarray [moth] ; documet.write ('Aual raifall = ' + aualraifall + ' mm') raiarray moth aualraifall (before) = 521 aualraifall (after) 521 Figure 2.7 raiarray showig how the total is icreased while iteratig through the for loop SAQ 2.4 (a) Write dow the JavaScript declaratio for the variable to hold the ruig total. (b) Where would you put this declaratio? Aswer to SAQ (a) The declaratio is var aualraifall. (b) It should go, together with the array declaratio ad ay other variable declaratios, at the begiig of the program. 16

17 Arrays ACTIVITY 2.4 (a) The file Program_8.2.4(a) cotais the code for workig out the aual raifall, as described above. Ope the file i Notepad ad read the code carefully. Calculate the total raifall either by had or by usig a calculator ad make a ote of your total. The ru the program to check whether you ad the program agree! (b) Now ru Program_8.2.4(b), which is supposed to do the same thig as Program_8.2.4(a). Observe the output, which will idicate that there s somethig wrog with the code. Ope the file Program_8.2.4(b) ad see if you ca idetify the problem. (c) Suppose that we ow require the total summer raifall, i.e. the raifall for the moths of Jue, July ad August. The file Activity_8.2.4 cotais a copy of Program_8.2.4(a). Ope this file i Notepad ad modify the code so that the program calculates ad writes out the total raifall for the moths of Jue, July ad August. You will eed to thik carefully about the startig value ad stoppig coditio for the for loop. Ru the program to check that it calculates ad outputs the correct value. Discussio (a) This has some similarities to the program you completed i Activity 5.6 of Uit 7. I this case though, the umbers are stored i the array, rather tha beig etered from the keyboard as i the earlier activity. (b) You may have spotted that although the variable aualraifall was correctly declared i Program_8.2.4(b), it had ot bee iitialised. Whe a attempt is made to add umbers to this udefied quatity the system reports that it is ot a umber (NaN). Not iitialisig variables appropriately is a commo source of errors i programmig, ad ofte leads to uexpected results. Although some laguages use default values whe variables are ot iitialised by the programmer, it is always safer to make the iitial values explicit i your code. (c) The chages required are as follows. Choose a suitable ame for the variable which will hold the total, e.g. summerraifall, or totalsummerraifall (remember to iitalise this to 0). Modify the for loop cotrol statemet as follows. for (var moth = 5; moth <= 7; moth = moth + 1) There are two chages here: to the startig value of the loop couter ad to the coditio. As you leared i Uit 7, a for loop ca be used for ay umeric rage. It does t have to start from 0 or 1. I this case we wat the raifall for the moths of Jue, July ad August, i.e. the raifall stored at idexes 5, 6 ad 7 (remember that Jauary raifall is stored at idex 0). A alterative coditio which would work correctly is moth < 8, but we thik our solutio is more ituitive. 17

18 Uit 8 Programs ad data Replace the variable ame i the body of the for loop ad i the output statemet by whatever you chose as the ew variable for the total. You will fid our workig program as Solutio_ Eterig data values ito a array I Subsectio 2.4 you saw that if all the data values are kow i advace the the array ca be declared ad its cotets iitialised to that particular set of values. For coveiece, all our examples so far have doe this, usig oe particular set of raifall data. However the great beefit of writig programs to ru o a computer is the flexibility that this gives us for carryig out the same set of operatios o differet sets of data values. I the real world, we ofte wat users to eter their ow collectios of data from the keyboard, ad there are two simple iput patters that we ca cosider at this poit. The program may require a fixed umber of data values to be processed, as i the raifall example where there will always be 12 values. The umber of data values may ot be kow i advace, e.g. i a program to process the exam marks for a class of studets, the umber of studets may vary from year to year. Usig the raifall example to illustrate the first of these situatios, where the umber of iput data values is fixed by the program, the algorithm is as follows. Before usig the values i calculatios, they would eed to be coverted to umbers usig parsefloat(). for each moth of the year prompt for the raifall figure for that moth ad put it ito the correct positio i the array ed for Traslatig this ito code ad usig widow.prompt()to allow the user to eter their data gives the followig code. var raiarray = ew Array(12); for (var moth = 0; moth < raiarray.legth; moth = moth + 1) raiarray [moth] = widow.prompt('eter raifall value','') Whe this code is executed, each data value retured by the prompt dialogue box will be placed i the array positio idexed by the curret value of moth. Sice raiarray.legth evaluates to 12, the for loop will termiate after 12 data values have bee read i (oe for each of the values of moth from 0 to 11, iclusive). 18

19 Arrays Usig the exam marks example to illustrate the secod situatio, we begi by promptig the user to eter the expected umber of values before eterig them. The structured Eglish versio could be writte: prompt user for umber of studets for each studet up to the specified umber prompt for the studet mark ad put it ito the correct positio i the array ed for We eed to declare a variable to hold the umber of studets to be etered, say umberofstudets, ad a variable to hold the array, say markarray. We ca traslate this ito JavaScript as follows. var umberofstudets; var markarray; umberofstudets = parsefloat(widow.prompt('how may studets do you have?', '')) Note the way i which we have combied the use of the prompt method ad the parsefloat() fuctio i a sigle statemet here. JavaScript would first evaluate the argumet to parsefloat() (i.e. the widow.prompt() statemet) ad the the call to parsefloat() itself. A alterative would have bee two separate statemets as follows: umberofstudets = widow.prompt('how may studets do you have?', ''); umberofstudets = parsefloat(umberofstudets) Now we kow the umber of studets, we ca create a suitably sized array ad assig it to markarray. markarray = ew Array(umberOfStudets); A for loop ca ow be used to prompt the user to eter the marks as follows. for (var studet = 0; studet < umberofstudets; studet = studet + 1) markarray[studet] = widow.prompt('eter studet mark', '') Whe you put all the code together it looks like the followig. var umberofstudets; var markarray; umberofstudets = parsefloat(widow.prompt('how may studets do you have?', '')) markarray = ew Array(umberOfStudets); for (var studet = 0; studet < umberofstudets; studet = studet + 1) markarray[studet] = widow.prompt('eter studet mark', '') 19

20 Uit 8 Programs ad data ACTIVITY 2.5 (a) Program_8.2.5(a) ad Program_8.2.5(b) cotai code illustratig the two approaches to readig data ito a array. Look at the code i these files ow, ad the ru each oe oce or twice with differet data values to see how they behave. (b) From a user viewpoit, these programs are less tha satisfactory because the output gives o idicatio of how far the iput process has progressed at ay poit. It would be very easy to forget which raifall figure or mark you had last etered! The file Activity_8.2.5 cotais a copy of Program_8.2.5(a). Ope the file i Notepad ad modify the lie of code iside the for loop so that the istructio displayed i the prompt box asks for the moth, e.g. for April, the text will be: Eter raifall value for moth 4 Hit Remember that the raifall for April will be stored at idex 3 of the array! Ru your program to check that it works correctly. Discussio (a) You should by ow be familiar with the use of for loops ad the legth property for processig arrays ad you should be able to see how the code does its job. (b) This was bit tricky, so do t worry if you did t get it quite right! The statemet eeded to produce the specified output is: raiarray [moth] = widow.prompt ('Eter raifall value for moth ' + (moth + 1),'') The first poit to ote is that i order to achieve the specified output you eeded to add 1 to the value of moth i the prompt statemet. That is, i order to get the raifall to be stored at idex 3 (which is the fourth idex i the array), you would eed a prompt askig the user to iput the raifall for moth 4. If you omitted the paretheses aroud moth + 1, as i the followig code: raiarray [moth] = widow.prompt ('Eter raifall value for moth ' + moth + 1, '') JavaScript would have iterpreted the secod + as the strig cocateatio operator. So, for example, if moth had the value 3, the prompt would have bee displayed as: Eter your raifall for moth 31 which is the cocateatio of the strig 'Eter raifall value for moth', the value of moth (which is curretly 3) ad the strig '1'. As metioed i earlier examples, code i paretheses is evaluated before the code i which it is ested. Our workig code is available as Solutio_

21 Arrays Fidig the maximum value i a array A commo statistic provided i weather reports is the maximum daily or mothly raifall durig a exteded period ad the date or moth i which it occurred. Suppose we wat a program to fid the largest amout of raifall that was recorded i ay moth of a give year. Startig with the first elemet, it would eed to iterate over the array, keepig a ote of the maximum value ecoutered so far. Whe the raifall for a moth is greater tha the curret maximum value, that moth s value becomes the ew maximum value. Whe all the values i the array have bee examied, the fial maximum value ca be writte out. Oce agai the for loop patter is appropriate to hadle this problem. I structured Eglish we ca express this activity as follows: iitialise maximum mothly raifall to raifall i first moth of the year for each moth of the year (except the first) compare the moth s raifall with the curret maximum if it is bigger replace the curret maximum with this moth s value ed for write out the fial maximum value SAQ 2.5 (a) What was the reaso for usig a for loop here, ad i the previous two examples? (b) The activity that takes place iside the for loop, (represeted i structured Eglish by the ideted sectio) ivolves a decisio. Ca you rewrite it more clearly usig the if structure that you met i Uit 7? Aswer to SAQ (a) I every case there was a fixed umber of elemets to process ad the same operatio was eeded o each elemet. (b) Usig structured Eglish we could write the decisio for comparig raifall figures as follows. if this moth s raifall is greater tha the curret maximum set curret maximum to this moth s raifall ed if Note that there is o eed for a else clause here, because if the value for the curret moth is ot greater tha the curret maximum we wat to leave the maximum value uchaged, so there is othig to do. Puttig all this together, ad usig the variable maxmothlyraifall to store the maximum value so far, the JavaScript code for carryig out the task is as follows. 21

22 Uit 8 Programs ad data maxmothlyraifall = raiarray [0]; for (var moth = 1; moth < raiarray.legth; moth = moth + 1) if (raiarray [moth] > maxmothlyraifall) maxmothlyraifall = raiarray [moth] ; documet.write('maximum mothly raifall = ' + maxmothlyraifall + ' mm') Note that the for loop couter starts with the value of moth beig 1 sice we have already used the first value i the array, with idex value 0, to iitialise our maximum mothly raifall. ACTIVITY 2.6 The file Program_8.2.6 cotais the JavaScript code for fidig the maximum raifall. (a) Study the code ad write dow the output you expect from the program. Check that the actual output is what you expected ad, if it is ot, try to work out why there is a differece. (b) The file Activity_8.2.6 cotais a copy of Program_ Ope the file i Notepad ad modify the program so that it outputs the smallest amout of raifall i ay moth istead of the largest. Ru your modified program to check that it works correctly. Discussio (a) From lookig at the values i raiarray, you would have expected the maximum mothly raifall to be 200. You should have foud this whe you ra the program! You ca also see from the data that this occurred i the third moth, March, but the program does ot cotai ay code to produce this iformatio. We pursue this i the ext subsectio. (b) The required chages are as follows. Chage the ame of the variable to somethig meaigful, e.g. mimothlyraifall throughout the program. The secod, ad crucial, chage is to chage the compariso operator i the if statemet from > to <, so thatitisavalue smaller tha the miimum so far that triggers executio of the body of the if statemet. The fial chage is to modify the wordig of the output statemet to reflect the chaged purpose of the program. Our solutio is available as Solutio_

23 Arrays Improvig the iformatio i the output EXERCISE 2.3 I its preset form, the iformatio produced by the two programs you have just studied is ot very iformative The user is likely to wat to kow ot just how much rai fell i the wettest (or least wet) moth but also which moth this was. How could you modify the maximum mothly raifall program so that it provided this additioal iformatio? Discussio You would eed to keep track of the idex of the elemet with the highest raifall so that the raifall at that idex could be retrieved, ad both pieces of iformatio provided for the user. I order to write the program discussed i Exercise 2.3 you eed a variable to store the value of the idex with the maximum raifall so far, say maxraifallidex. This will iitially be set to 0, the first idex i the array, ad will be updated to the curret idex each time a higher raifall value is foud. Here is the relevat fragmet of code. maxraifallidex = 0; for (var moth = 1; moth < raiarray.legth; moth = moth + 1) if (raiarray [moth] > raiarray [maxraifallidex]) maxraifallidex = moth Note that we do t eed to record the actual value of the curret maximum raifall, because we ca fid it i the array raiarray usig maxraifallidex. Figure 2.8(a) shows the idex of the maximum raifall beig updated whe a raifall value higher tha the curret maximum value is ecoutered; Figure 2.8(b) shows the situatio where o update occurs because the raifall value is ot greater tha the curret maximum. As Program_8.2.7 (referred to below) shows, it is ot ecessary to hold both values throughout the program. 23

24 Uit 8 Programs ad data raiarray moth before compariso maxraifallidex is > 115 so update maxraifallidex after compariso maxraifallidex is ow 2 (a) Updatig maxraifallidex raiarray before compariso maxraifallidex is moth is ot > 200 so o chages eeded after compariso maxraifallidex is still (b) A situatio whe o updatig occurs Figure 2.8 EXERCISE 2.4 Whe the ed of the loop i Exercise 23 has bee reached, both the maximum mothly raifall ad the umber of the moth i which it occurred (e.g. Jue is moth 6) should be writte out. Add the JavaScript expressios where idicated below. documet.write('maximum Mothly Raifall of ' + expressio for maximum raifall should go here + 'mm occurred i moth ' + expressio for moth i which maximum raifall occurred should go here) 24

25 Arrays Discussio The expressio for the maximum raifall is raiarray [maxraifallidex]. The expressio for the moth is (maxraifallidex + 1). Remember from Activity 2.5 that you eed to add oe to the idex to adjust for zero-based idexig, ad to eclose the expressio i paretheses to esure that the + symbol is iterpreted as additio rather tha cocateatio. The full output statemet is: documet.write('maximum Mothly Raifall of ' + raiarray [maxraifallidex] + ' mm occurred i moth ' + (maxraifallidex + 1)) The full code for the program which outputs both the maximum raifall ad the moth i which it occurs is available as Program_ I the ext subsectio you will see how to write out the actual ame of the moth. 2.7 Usig parallel arrays I discussig the code for writig out the maximum mothly raifall we said that there were problems i the way that the moth was output. Most users would prefer to kow that a evet occurred i April, rather tha i the fourth moth of the year. Is there aythig we ca do about this? Well, we could store the ames of the moths i a secod array ad the look up the moth ame whe we eed it. Here is a appropriate declaratio. var mothnamesarray = ['Jauary','February',...,December'] As show i Figure 2.9, you will otice that each moth ame appears at the same positio i this array as the correspodig raifall i raiarray. If we kow the idex for which the maximum raifall occurred, which we called maxraifallidex, we ca access the correspodig moth ame as mothnamesarray [maxraifallidex] ad iclude this i our write statemet as follows: documet.write('maximum Mothly Raifall of ' + raiarray [maxraifallidex] + 'mm occurred i ' + mothnamesarray [maxraifallidex]) Arrays i which the iformatio held at the same idex i two or more arrays is related (as i the two we have just discussed) are kow as parallel arrays. 25

26 Uit 8 Programs ad data raiarray mothnamesarray maxraifallidex 'Jauary' 1 'February' 2 'March' 3 'April' 4 'May' 5 'Jue' 6 'July' 7 'August' 8 'September' 9 'October' 10 'November' 11 'December' output Maximum Mothly Raifall of 200 mm occurred i March Figure 2.9 Parallel arrays for raifall ad moth ame ACTIVITY 2.7 The file Activity_8.2.7 cotais a partially complete program for displayig the maximum mothly raifall ad the moth (by ame) i which it occurs. Ope this file ad add the missig code i the places idicated. We have discussed all aspects of the program above, so i this activity you simply eed to idetify the appropriate code fragmets to iclude. Oce you have completed your program, ru it to check that it produces the expected output. Discussio Your program should have displayed the followig output. Maximum mothly raifall of 200 mm occurred i March A full solutio is available as Solutio_ SAQ 2.6 How could this ew array of moth ames be used to improve the output from the program i the file Program_8.2.3, which coverted the raifall figures from mm to iches? Aswer to SAQ If we iclude the declaratio ad iitialisatio of mothnamesarray at the begiig of the program, we ca the iclude the ame of the relevat moth, as well as the amout of raifall for each moth, i the write statemet i the for loop. 26

27 Arrays ACTIVITY 2.8 The file Activity_8.2.8 cotais a copy of Program_ Ope the file i Notepad ad modify the program so that the ames of the moths (stored i mothnamesarray) are prited out alogside the correspodig raifall values. Ru your modified program to check that it works as expected. Discussio Your modified output statemet (i the secod for loop) should be somethig like the followig. documet.write(mothnamesarray [moth] + ' : ' + ichraiarray [moth] + '<BR>') This is a much more satisfactory way of iformig the user which moth is beig referred to. Not oly are we able to provide the moth ame istead of its umber but it also makes the code more straightforward as we do ot eed to worry about compesatig for the fact that our arrays are zerobased. Our full solutio for this activity is available as Solutio_ Maagig the precisio of umeric output The default way i which JavaScript hadles umbers with decimal poits is ot particularly helpful, as you ca see from lookig at the list of values produced whe you ra the program i Activity 2.8. There are far too may figures after the decimal poit at least five, ad i some cases more. We do ot really wat to kow that the Jauary raifall value of 111 millimetres is about iches! JavaScript provides us with a way of roudig decimal umbers to the earest whole umber through use of its Math object, which has a associated method called roud(). For example, Math.roud(2.4) evaluates to 2 Math.roud(2.7) evaluates to 3. However, this is ot etirely suitable for our purpose as you will see i Activity 2.9. ACTIVITY 2.9 (a) Look at the code i the file Program_8.2.9 where you ca see the use of Math.roud() i a attempt to get rid of the uwated precisio of our raifall coversio figures. (b) Ru the program to see what effect it has o the output values. You should see somethig similar to Figure

28 Uit 8 Programs ad data Figure 2.10 Screeshot of output from Program_8.2.9 Ca you see ay remaiig problems with the precisio of the output values? Discussio (a) We chose to roud the raifall figures immediately after their coversio to iches. A alterative would have bee to iclude the code for roudig i the output statemet istead, as follows. for (var moth = 0; moth < ichraiarray.legth; moth = moth + 1) documet.write(mothnamesarray [moth] + ' : ' + Math.roud(ichRaiArray [moth]) +' i(s)' +'<BR>') This would have bee a better solutio if we thought we might eed our results i the ichraiarray for further calculatios later o, ad so wated to retai their precisio. (b) You may have oticed from the output that by roudig to whole umbers we have lost too much precisio. For example both the May figure of 23 mm ad the December figure of 37 mm ow get displayed as 1 i, although they were sigificatly differet before coversio. You will see i Sectio 3 how this ca be improved by developig a small piece of code that produces umeric values to two decimal places. This would provide a more appropriate degree of precisio for our raifall figures, with the May ad December figures becomig 1.06 i ad 1.46 i, respectively. 28

29 Arrays 2.9 Summary I this sectio, we itroduced you to the array as a example of a data structure ad looked at examples of the use of Array objects to store ad process collectios of data. We discussed some commo patters of array processig such as readig i ad displayig their cotets, addig the elemets i a array ad fidig the largest or smallest elemet i a array. You also saw the power of parallel arrays for storig related data. Fially, we discussed the precisio of figures produced as a result of calculatios i JavaScript ad the roud() method of the Math object for roudig to whole umbers. 29

30 Uit 8 Programs ad data 3 Fuctios This sectio aims to: itroduce you to the use of fuctios as a way of simplifyig the structure of large programs by breakig them dow ito smaller, amed, pieces of code; explai how fuctios allow us to wrap up the code for a specific activity i such a way that it ca be reused withi a program, or eve used i other programs; demostrate how to use, ad write, fuctios i JavaScript; demostrate how fuctios with argumets provide a way of hadlig abstractio. 3.1 Dealig with subtasks i programs Most of the programs you have met so far are very simple, i the sese that they carry out oly a sigle task, usig a few statemets. The problems that we wat to solve i real life are usually more complicated tha this, possibly ivolvig hudreds of activities ad requirig millios of lies of code, as with the word-processor applicatio that created this documet. Oe way to reduce the complexity of programs is to break the mai task dow ito a collectio of subtasks. If some of the subtasks are themselves fairly complex, the they will eed to be broke dow further ito subsubtasks, ad so o. We ca the write a separate piece of code for each subtask ad a cotrollig program to lik all these special purpose pieces of code together, as ad whe they are required. Each piece of code that carries out a subtask eeds to be give a meaigful ame so that it ca be referred to wheever it is eeded as part of a program. It may also eed data to carry out its specified task ad to provide the mai program with ay results that it has computed. 3.2 Usig fuctios i JavaScript JavaScript provides fuctios as a way of hadlig subtasks. You met oe fuctio parsefloat(), which coverts strigs ito umbers, i Uit 7. Before you lear how to write JavaScript fuctios, we will itroduce you a few other simple fuctios writte by the course team. 30

31 Fuctios The drawbox() fuctio Our first fuctio is amed drawbox(). It carries out the task of drawig a outlie box, of a fixed size, 4 characters high by 12 characters wide, usig the '*' character to form the sides of the box. Oce the code for the drawbox() fuctio is writte, the fuctio call drawbox() ca be added at the relevat poit i the mai program. The drawbox() fuctio does t require ay data (ulike the parsefloat() fuctio), ad so has o argumets, but we still eed to iclude the paretheses () after the ame. I choosig our fuctio ames, we shall follow the same M150 style guidelies as for variables. The drawcolouredbox() fuctio A similar fuctio, drawcolouredbox() draws a box 8 characters high by 16 characters wide, but it has a sigle argumet which allows us to specify the colour i which the box is to be draw. For example, we might use this fuctio i our program with the followig statemet. drawcolouredbox('blue') Note that the ame of the colour is eclosed i quotes. JavaScript provides a huge rage of predefied colours for our use. You will fid a list of the predefied colours i some JavaScript textbooks, or by searchig o the web. However, if you experimet, you will fid that most commo colours will be recogised. The drawsizedbox() fuctio Aother fuctio, drawsizedbox(), has two argumets, which allow us to specify the height ad width of the box to be draw, so that drawsizedbox(6,10) draws a box 6 characters high by 10 characters wide. Argumets are sometimes referred to as parameters. The three fuctios we have discussed so far carry out some task but, ulike parsefloat(), they do ot retur ay result for use later i the program. I some programmig laguages this type of fuctio is kow as a procedure. Before studyig a program which uses our fuctios we will itroduce oe further fuctio, which does retur a result. The calculatearea() fuctio The fuctio calculatearea() has two argumets, the height ad width of a rectagle (or box). The fuctio calculates the area of the rectagle, ad returs this result. You will recall from Uit 7 that whe a fuctio returs a value, we eed some way of usig the retured value, either straight away as i a output statemet, or for future use i our program by assigig it to a variable. Here are examples which illustrate both uses for the calculatearea() fuctio. The first writes out the area of a box, while the secod calculates the area of a box ad saves it for future use. documet.write('the area of a box with height 6 ad width 10 is ' + calculatearea(6,10) + '<BR>') var boxarea; boxarea = calculatearea(6,10) 31

32 Uit 8 Programs ad data ACTIVITY 3.1 The file Program_8.3.1 cotais code which uses the four fuctios described above. We are ot particularly iterested i the code for the fuctios at this stage, ad so we have put this i a separate file. Ope the file i Notepad ad study the way i which the fuctios are used. The ru the program. The file Activity_8.3.1 cotais a copy of Program_ Ope this file i Notepad ad add statemets i the places idicated to do the followig. (a) Draw aother simple box. (b) Draw a brow box. (c) Draw a box whose size is 3 characters deep by 20 characters wide. (d) Calculate ad write out the area of a box with height 5 ad width 3. Ru your modified program to check the effects of your additioal statemets. Discussio Here are the lies of code you should have added to the program. (a) drawbox() (b) drawcolouredbox('brow') (c) drawsizedbox(3,20) (d) documet.write('the area of a box with height 5 ad width 3 is ' + calculatearea(5,3) + '<BR>') You will fid our completed program as Solutio_ The fuctios for Activity 3.1 are stored i a separate file, called uit8fuctios.js. This eed ot cocer you at preset, but you will lear more about usig separate files cotaiig fuctios i Uit 9 I Activity 3.1 we used existig fuctios that carry out specified tasks, providig appropriate values (as argumets) where ecessary. For the rest of this sectio we look at various aspects of defiig ad usig our ow fuctios. 3.3 Writig fuctios i JavaScript The sytax for writig (or defiig, to use the more usual termiology) a simple JavaScript fuctio ca be see i the followig example. fuctio dothis() documet.write('do this' + '<BR>') There are four importat parts of this defiitio: the first three form the fuctio header ad the fourth is the fuctio body. 32

33 Fuctios 1 The reserved word fuctio which idicates that what follows is a fuctio defiitio. 2 The ame of the fuctio, which i our example is dothis. 3 A list of argumets eclosed i paretheses. This simple fuctio does ot eed ay data passed to it, so the argumet list () is empty. 4 The body of the fuctio, which is the set of statemets that carry out the work of the fuctio. These are eclosed i curly braces.ithe example give, the body cotais a sigle documet.write() statemet but a fuctio ca cotai ay of the statemets you would fid i a mai program, ad there ca be ay umber of them though it is good practice to keep fuctios short ad focused. To iclude ad use this fuctio i a program techically we say that we call or ivoke the fuctio we place the code for the fuctio at the begiig of our program. We the place a statemet ivokig the fuctio (the fuctio call) i the code at the poit where we wat it to carry out its task, as i Activity 3.1. Here is the JavaScript code of Program_8.3.2, which illustrates the defiitio of a umber of fuctios ad a call to each of them. Note that all the fuctios i this program are show as writig out somethig. This is because we wat you to have some visible idicatio of the fuctios workig. Fuctios ca, of course, do all sorts of other thigs, as you have see with the parsefloat() fuctio ad our ow calculatearea() fuctio. // first defie a few fuctios fuctio dothis() documet.write('do this'+ '<BR>') ; fuctio dothat() documet.write('do that' + '<BR>') ; fuctio dotheother() documet.write('do the other' + '<BR>') ; // the call each of them i our program dothis(); dothat(); dotheother() The last three lies are called fuctio calls because they each call (ivoke) a fuctio. The code for fuctios ca ormally be placed aywhere i JavaScript source code. I M150 we place them before the statemets of the mai program. ACTIVITY 3.2 Ru Program_8.3.2 to see how it works. The file Activity_8.3.2 cotais a copy of Program_ Ope this file i Notepad ad add the defiitio for a ew fuctio amed doitagai(), which writes out the message 'do it agai'. You should also add a fuctio call which uses your ew fuctio. Ru the modified program to test your code. 33

34 Uit 8 Programs ad data Discussio Here is the defiitio for the fuctio doitagai() fuctio doitagai() documet.write('do it agai' + '<BR>') ad here is the fuctio call: doitagai() Remember that you eed to iclude the paretheses after the fuctio ame, eve whe the argumet list is empty. You will fid the complete program i Solutio_ Fuctios with argumets It ofte happes that a idetical subtask eeds to be carried out i several differet places withi a mai program. Oce defied, a fuctio ca be called as may times as required. I other situatios, the ature of the repeated subtask may be such that almost everythig is the same, but some aspects chage i a way that ca be maaged by providig suitable argumets to the fuctio, as with some of the fuctios whose use was demostrated i Activity 3.1. Argumets allow us to geeralise (or abstract) the fuctioality of our code by lookig for patters of activity which are repeated i a similar but ot idetical way. Abstractio i the cotext of programmig refers to the way i which the details of a particular task (e.g. the specific values eeded by a fuctio) ca be igored, so as to cocetrate o the more geeric aspects of the task (such as the processig that a fuctio will do o ay set of suitable values). The body of the fuctio captures the commo behaviour of the patters, while the argumets allow us to provide values that capture those aspects i which the patters differ o each occasio. As a simple example of how to defie a fuctio with a argumet, cosider the fuctio dothis(), ad suppose that the task to which it refers may eed to be doe at differet times of day or o differet occasios. Whatever the task, we might wat to do it ow or later or eve evetually. We ca make the time at which we do it ito a argumet for our fuctio by expadig the origial defiitio as follows. fuctio dothis(atime) documet.write('do this ' + atime + '<BR>') The argumet atime is oly meaigful iside the fuctio defiitio where it ca be used like a variable. Its value is ot available outside the fuctio. Whe the fuctio is called, a actual value for the argumet must be used. For example, whe the fuctio call dothis('ow') 34

35 Fuctios is executed, the actual strig 'ow' replaces the argumet ame atime i the followig statemet. documet.write('do this ' + atime + '<BR>') SAQ 3.1 Assume that the fuctio dothis(atime) has bee defied. (a) What output will be produced whe the statemet dothis('ow') is executed? (b) What output will be produced whe the statemet dothis('evetually') is executed? Aswer to SAQ (a) The output will be do this ow. As explaied above, the argumet 'ow' will replace atime i the body of the fuctio, so the documet.write() statemet will cocateate ad output the strigs 'do this' ad 'ow' ad move to the ext lie. This is show i Figure 3.1. call execute resultat output dothis('ow') 'ow' fuctio dothis(atime) 'ow' documet.write('do this' + atime + '<BR>'); do this ow I Figure 3.1 ad some of the figures which follow, we have show the fuctio call before its defiitio. This is for visual clarity oly. A fuctio call should ormally follow its defiitio. Figure 3.1 Defiitio ad use of dothis() showig the effect of a fuctio argumet (b) The output will be do this evetually. I this case, atime will be replaced i the body of the fuctio by 'evetually'. ACTIVITY 3.3 The file Activity_8.3.3 cotais the defiitio of the fuctio dothis(), together with three fuctio calls, each oe with a differet value for the argumet. You should execute this file to see what it does, the ope it i Notepad ad add the defiitio of a ew fuctio amed doitagai(), which should also take the argumet atime ad which, if used i the fuctio call doitagai('ow'), writes out the message: do it agai ow 35

36 Uit 8 Programs ad data Add a fuctio call, which you should place after the other fuctio calls i the program, that uses your ew fuctio with 'ow' as the argumet, the ru the modified program to check that it works as iteded. Discussio Here is our defiitio for the fuctio doitagai(). fuctio doitagai(atime) documet.write('do it agai ' + atime + 'BR') The fuctio call is: doitagai('ow') Our modified program is available as Solutio_ Fuctios which retur a value The JavaScript fuctios defied so far carry out simple procedural tasks, i.e. oes that do ot ivolve returig a value to the program that called the fuctio. There is aother category of fuctios that carry out some sort of computatio ad provide a value as the result of that computatio. The value retured ca be used i a program i various ways: for example, it might be assiged to a variable or used directly i some further computatio or just writte out. You may recall from Uit 7 that such fuctios are said to retur a value to the program which calls them. I order to do this, JavaScript provides us with a special statemet, the retur statemet, which cosists of the reserved word retur followed by the value it eeds to retur. As a example of a useful fuctio of this type, we will revisit the raifall example from Sectio 2. A clearly idetifiable subtask which we ca imagie beig of use i a umber of other cotexts, other tha the raifall program, is the coversio of millimetres to iches. This is therefore a obvious cadidate for implemetatio as a fuctio. If we ame the fuctio toiches(), ad provide it with a argumet, umberofmm, which represets the value i millimetres that we wat coverted to iches, the we ca defie the fuctio as: fuctio toiches(umberofmm) retur umberofmm * The actual value that is passed to the fuctio as the argumet umberofmm will be multiplied by ad the resultig value (a umber of iches) will be retured to the mai program for subsequet use. For example, to calculate the umber of iches of raifall which correspod to the 200 mm that fell i March, ad to assig the resultig value to a variable called marchiches, you could write 36

37 Fuctios marchiches = toiches(200) or, if all the raifall figures are stored i raiarray, you could write marchiches = toiches(raiarray [2]) I the secod example, you ca see that the argumet passed to a fuctio does ot have to be a explicit umeric value, but ca be the ame of some variable or a expressio provided it evaluates to a umber. If you wated to write out the value retured by the fuctio, the you could use the fuctio directly i a statemet such as documet.write('march raifall was ' + toiches(raiarray [2]) + ' iches' + '<BR>') Figure 3.2 shows the effect of callig the toiches() fuctio with a argumet of 200. call execute result marchiches = toiches(200) 200 fuctio toiches(umberofmm) 200 retur umberofmm * ; * = Figure 3.2 The toiches() fuctio, showig the effect of callig it with a argumet of 200 ACTIVITY 3.4 (a) Program_8.3.4 icludes the defiitio ad use of the toiches() fuctio. Study the code ad the ru the program ad check that the output is as you expected, preferably usig a calculator to check the values. (b) The file Activity_8.3.4 cotais a HTML template for a JavaScript program. Ope this file i Notepad ad add JavaScript code to defie a fuctio called togallos(),which calculates the umber of gallos correspodig to a umber of litres. The relevat coversio iformatio is: 1 litre = gallo. Add statemets i the mai program which ivoke your fuctio to covert ad output the umber of gallos equivalet to 20 litres, 35 litres ad 55 litres. Ru your program ad make a ote of the results of the three coversios specified. 37

38 Uit 8 Programs ad data Discussio The argumets specified i a fuctio defiitio are referred to as formal or dummy argumets, ad the argumets i a fuctio call as actual argumets. (a) The output from Program_8.3.4, which uses toiches(), should have coviced you that a fuctio call results i the body of the fuctio beig evaluated, with the actual argumet i the fuctio call replacig the formal argumet. For example, i the first fuctio call the value 27 would have bee substituted for umberofmm, resultig i a calculatio of 27 * The result of this calculatio would have bee retured to the mai program, coverted to a strig, cocateated with the other strigs i the documet.write() statemet, ad writte out. (b) Here is our defiitio for the coversio fuctio. (You may have chose a differet ame for the fuctio argumet.) fuctio togallos(umberoflitres) retur umberoflitres * Your statemets to use the fuctio should be similar to the followig. documet.write('20 litres is ' + togallos(20) + ' gallos' + '<BR>' The results of the coversios, as displayed i the program output, should have bee as follows. 20 litres is gallos 35 litres is gallos 55 litres is gallos Our workig code for this activity is available as Solutio_ A fuctio to tidy up the umeric output You probably oticed whe you ra Program_8.3.4 i Activity 3.4 that there were problems with the precisio of the results similar to those discussed i Subsectio 2.9. What is eeded is a method to roud a umeric value to a specified umber of decimal places. We ca write a very simple fuctio to provide a precisio of two decimal places. This fuctio ca the be used wheever ecessary by icludig it i the program code. Here is its defiitio: fuctio twodps(aynumber) retur Math.roud(100 * aynumber) / 100 The fuctio has a reasoably meaigful ame, twodps, ad a argumet, aynumber, which is the umber to be rouded. It makes use of the roud() method from the Math object which you met i Subsectio

39 Fuctios How does the fuctio work? Here is a brief explaatio of how this fuctio works mathematically. First multiply the umber by 100, which moves the decimal poit two places to the right (so that there are two more digits i frot of the poit); the roud the result to the earest whole umber, usig the roud() method; fially, divide by 100, which moves the decimal poit two places to the left. Here is a example, usig the umber , oe of the results from Program_8.3.4: * 100 gives Roudig this to the earest whole umber gives 319. Dividig 319 by 100 gives 3.19, which is the origial result rouded to two decimal places. By movig the decimal poit (ad the movig it back agai) we have bee able to use the roud() method to obtai greater accuracy. We ca ow add the defiitio of the twodps() fuctio to the program file cotaiig toiches() ad use it to improve the precisio of the value retured by the latter fuctio. To do this we replace the statemet retur umberofmm * i the body of the toiches() fuctio by retur twodps(umberofmm * ) The secod statemet takes the umber which is calculated from umberofmm * as the argumet for the twodps() fuctio ad returs that umber correct to two decimal places. This is a very simple example of estig fuctio calls: the result retured from oe fuctio is used withi the code of aother fuctio before their combied result is retured. Program_8.3.5 cotais the modified versio of the toiches() fuctio, together with some fuctio calls to ivoke it. The first part of the program defies the fuctio. fuctio twodps(aynumber) retur Math.roud(100 * aynumber) / 100 The the toiches() fuctio, which uses the twodps() fuctio is defied. fuctio toiches(umberofmm) retur twodps(umberofmm * ) Either or both fuctios ca be used i our mai program with a variety of differet argumets. 39

40 Uit 8 Programs ad data call execute call execute marchiches = toiches(200) 200 fuctio toiches(umberofmm) 200 retur twodps(umberofmm * ); fuctio twodps(aynumber) retur Math.roud(100 * aynumber) / result Figure 3.3 Code from Program_8.3.5 showig a fuctio callig aother fuctio ACTIVITY 3.5 I Activity 3.4 (b) you wrote a fuctio to covert measuremets of volume from litres to gallos. The file Activity_8.3.5 cotais a workig copy of the program that icluded this fuctio. Ope it i Notepad ad modify the program so that it produces aswers correct to two decimal places of accuracy. The ru the program to test your code. Discussio Here is our modified defiitio for the fuctio togallos(). fuctio togallos(umberoflitres) retur twodps(umberoflitres * ) The oly other modificatio eeded is the iclusio of the twodps() fuctio defiitio i your program. The coverted values for 20, 35 ad 55 litres are ow retured as 4.40, 7.70 ad gallos, respectively (although the fial zeros are ot displayed i the browser widow). Solutio_8.3.5 is a workig versio of the code for this activity. 3.7 Fuctios with more tha oe argumet I Sectio 5 of Uit 7 you looked at a program i which the user was prompted to iput a umber ad a character, ad the program the used a for loop to prit the specified umber of the chose character o a sigle lie of output, e.g. seve asterisks ('*'). I this subsectio, we cosider how such a patter of activity might be captured i oe or more fuctios. 40

41 Fuctios A simple but useful fuctio would be oe that prited lies of asterisks across a output page, i order to separate various sectios of output text. At its simplest level, each time this fuctio is called it could write a fixed umber of asterisks as a sigle lie ad the move to the ext lie. If we ame this fuctio pritstarlie, ad decide that the stadard legth of lie is 40 characters, the we ca write the followig fuctio defiitio. fuctio pritstarlie() for (var positio = 1; positio <= 40; positio = positio + 1) documet.write('*') ; documet.write('<br>') Note that after usig a for loop for the repetitio, a <BR> tag is eeded to move to the ext lie of output. Havig see this fuctio you might be struck by the fact that there is a easily reusable patter here, because the legth of the lie could be varied by itroducig a argumet to specify the umber of asterisks. EXERCISE 3.1 (a) Write dow the defiitio of a fuctio, pritstars(), which has a umber, say anumber, as a argumet, ad which displays a lie of asterisks of legth anumber i the output widow. (b) Write dow a fuctio call which uses the pritstars() fuctio to output a lie of 25 asterisks. Discussio (a) Here is our fuctio defiitio. fuctio pritstars(anumber) for (var positio = 1; positio <= anumber; positio = positio + 1) documet.write('*') ; documet.write('<br>') Note how the argumet, anumber, is used to replace the specific value, 40, used i the defiitio of the pritstarlie() fuctio. (b) Here is the fuctio call eeded to write out a lie of 25 asterisks. pritstars(25) Remember that whe ivokig a fuctio we do ot eed to use a explicit value as a argumet. We may well wat to use a variable or some other appropriate expressio. If, for example, a variable with ame mynumber had bee declared ad assiged a umber earlier i the program, the fuctio call pritstars(mynumber) 41

42 Uit 8 Programs ad data would be perfectly valid. The code for the fuctios pritstarlie() ad pritstars(), alog with statemets which use them with suitable argumets, ca be foud i the file Program_ There are several other ways this fuctio could be geeralised to accommodate a eve wider rage of essetially similar patters. Aother useful variatio would be to allow the user to specify the character to be used, e.g.'!' or '$' by addig aother suitable formal argumet to the list i the fuctio header ad modifyig the code i the body of the fuctio to use this argumet appropriately, ad the ivokig the fuctio with appropriate actual argumets i the body of our program. SAQ 3.2 Write dow a suitable ame for a fuctio which takes two argumets, a umber ad a character, ad which displays a lie of the specified characters, of legth equal to the specified umber. Aswer to SAQ As we called our fuctio to prit asterisks ( star characters) pritstars(), it would be cosistet to call this oe pritcharacters() but you may have thought of a equally suitable ame. EXERCISE 3.2 List the chages that would eed to be made to the code of the fuctio defiitio for pritstars()to produce a fuctio defiitio for pritcharacters(). Discussio There are essetially three chages eeded. We eed to chage the ame of the fuctio from pritstars to pritcharacters. We eed to add aother argumet after anumber i the argumet list. Where there are several argumets for a fuctio, they are separated by commas. The ew argumet should have a meaigful ame such as outputcharacter, so the ew fuctio header would become somethig like: fuctio pritcharacters(anumber, outputcharacter) We also eed to modify the body of the fuctio so as to replace the specific character, '*' by the more geeral argumet, outputcharacter. 42

43 Fuctios SAQ 3.3 Write dow fuctio calls which ivoke the pritcharacters() fuctio i order to display: (a) a lie of 10 '@'s; (b) a lie of 25 ' 's; (c) our origial lie of 40 '*'s. Aswer to SAQ The required fuctio calls are: (a) pritcharacters(10,'@') (b) pritcharacters(25,'-') (c) pritcharacters(40,'*') ACTIVITY 3.6 The file Activity_8.3.6 is a copy of Program_8.3.6, which cotais code for the fuctios pritstarlie() ad pritstars(), alog with statemets which use them with suitable argumets. Study the code i this file ad the ru Program_8.3.6 to remid yourself what each fuctio does. Oce you are sure you uderstad how the fuctios work, add code to defie the pritcharacters() fuctio discussed above ad test it usig the fuctio calls from SAQ 3.3. Discussio Here is the code for the pritcharacters() fuctio. fuctio pritcharacters(umber, outputcharacter) for (var positio = 1; positio <= umber; positio = positio + 1) documet.write(outputcharacter) ; documet.write('<br>') Note the way i which the formal argumets i the fuctio header are separated by commas. Workig code is provided as Solutio_ There is oe further geeralisatio of the prit patter, which allows a twodimesioal output. Suppose we wat a fuctio to output a block of characters, say five lies, each of 15 '*'s, or 12 lies, each of 24 '$'s. To do this we will eed a third argumet, to hadle the umber of lies of characters we wat to output. 43

44 Uit 8 Programs ad data To start with a cocrete example let s thik about a block of five lies, each of 15 '*'s. You already kow how to output a sigle lie of 15 '*'s, so all you eed to do is to repeat this five times, to obtai the followig output. *************** *************** *************** *************** *************** I the code for displayig a sigle lie of characters, we used a for loop. To repeat this display, we will eed to use aother for loop, i which the body will be the first for loop, together with a statemet to move the output to a ew lie. I structured Eglish we could write our algorithm as: for each lie from 1 to 5 for each positio from 1 to 15 write the character '*' ed for move to a ew lie ed for We should of course be lookig for the more geeral patter that will allow us to draw a block of ay specified size, made up of ay specified character, so we eed to replace the values 5, 15 ad * by more geeral argumets, which ca vary from oe use of the fuctio to aother, as follows. for each lie from 1 to umber of lies for each positio from 1 to umber of characters per lie write the give character ed for move to a ew lie ed for The correspodig fuctio defiitio ca be writte as: fuctio pritcharacterblock (lies, umber, outputcharacter) for(var lie = 1; lie <= lies; lie = lie + 1) for(var positio = 1; positio <= umber; positio = positio + 1) documet.write(outputcharacter) ; documet.write('<br>') We have used the meaigful ame pritcharacterblock() for the ew fuctio ad we have used three argumets, to represet the three aspects of the ew patter that will vary. 44

45 Fuctios call execute resultat output of five lies of 15 '*'s pritcharacterblock(5, 15, '*'); 5 15 '*' fuctio pritcharacterblock(lies,umber,outputcharacter) 5 for (var 15 for (var positio = 1;positio <= umber; positio = positio + 1) '*' documet.write(outputcharacter) ; documet.write('br') *************** *************** *************** *************** *************** Figure 3.4 Output from the statemet pritcharacterblock(5,15,'*') showig liks from argumets through fuctio code to output ACTIVITY 3.7 You will fid code for implemetig pritcharacterblock() i the file Program_8.3.7, together with some fuctio calls. Study the code, the ru the program to see the output it produces for various values of the argumets. Discussio You should have foud that the fuctio is quite powerful, allowig you to produce a wide rage of rectagular patters. You ca, of course, use ay character from the keyboard as your output character, icludig umbers ad letters. EXERCISE 3.3 Ca you thik of aother way i which we could have implemeted the pritcharacterblock() fuctio? Hit Are there ay existig fuctios that you could reuse? 45

46 Uit 8 Programs ad data Discussio The fuctio, pritcharacters() outputs a specified umber of a particular character o a sigle lie. This fuctio could be used by ivokig it i the defiitio of pritcharacterblock() as follows. fuctio pritcharacterblock(lies, umber, outputcharacter) for (var lie = 1; lie <= lies; lie = lie + 1) pritcharacters(umber, outputcharacter) Of course, you would eed to esure that the defiitio of pritcharacters() was available i the program. 3.8 Code reuse As illustrated i Exercise 3.3, the pritcharacterblock() fuctio could have bee implemeted by reusig the fuctio pritcharacters(). I additio to reusig a fuctio at several differet places i a program to save writig the same code more tha oce, you ca also reuse it as part of the defiitio of other fuctios. This helps to maage the level of complexity of the code ad should make it easier to uderstad. Exercise 3.3 also shows that there are sometimes a umber of differet ways i which a fuctio body ca be writte. As someoe usig the fuctio, all you eed to kow is the type of argumets it requires, ad what the fuctio does; these are idetical for both defiitios. The detailed code i the fuctio body is of o particular iterest, ad ideed could be chaged without havig ay impact o your program. This is oe of the aspects of abstractio that arises from usig fuctios. I some cases the ature of the subtask may be such that the fuctio code ca be reused i aother program altogether. Wheever a fuctio captures a patter of useful activity that is likely to occur regularly i differet situatios, it ca be retaied for future use, rather tha havig to rewrite it each time. The twodps() fuctio from Subsectio 3.5 has already proved itself to be such a fuctio. I Uit 9 we look at ways of creatig ad orgaisig libraries of useful fuctios. 46

47 Fuctios 3.9 Hits for writig fuctios Here are a few questios you might wat to ask yourself whe desigig ad writig fuctios. Why write a fuctio? Is it eeded to carry out a specific, clearly defied task? Is it likely to be useful elsewhere i your program or i other programs? How to desig the fuctio Does it eed ay argumets ad, if so, how may? Is the fuctio procedural (such as the fuctios to write out patters of characters) or does it eed to retur a value? Are there ay existig fuctios that could be reused withi the defiitio either fuctios provided by JavaScript or those that you have writte yourself? Have you chose meaigful ames for your fuctio ad ay argumets? We develop some of these ideas i Uits 9 ad 10. ACTIVITY 3.8 I this activity you are goig to write a simple fuctio from scratch. The fuctio, called maxnumber() will retur the larger of two umbers, which are provided as its argumets. For example, maxnumber(3,5) would retur 5; maxnumber(7,2) would retur 7. For simplicity, if the two umbers are the same, the the fuctio should just retur either of the umbers, i.e. maxnumber(2,2) will retur 2. This activity will give you the opportuity to apply what you have leared about fuctios ad to revise some of what you leared i Uit 7. The file Activity_8.3.8 cotais a program template which also provides some statemets for testig your fuctio. (a) Ope the file i Notepad ad add your fuctio where we have idicated. Hits You will eed to use a if...else statemet i your fuctio i order to determie which umber eeds to be retured. You will eed to choose a appropriate compariso operator to useiyour if coditio. (b) Ru the program ad check that you get the expected output. 47

48 Uit 8 Programs ad data Discussio (a) Here is our solutio. Yours may differ slightly; for example, you might have used differet variable ames or you could have used >= istead of >. fuctio maxnumber(firstnumber, secodnumber) if (firstnumber > secodnumber) retur firstnumber else retur secodnumber (b) The output from your program should have bee: The larger of 3 ad 7 is 7 The larger of 7 ad 3 is 7 The larger of 2 ad 2 is 2 The larger of 5 ad 5 is 5 The larger of 0 ad 2 is 0 You will fid our completed program as Solutio_ Summary I this sectio, we itroduced you to the idea of breakig dow programs ito fuctios i order to reduce the complexity of the resultig code ad to facilitate the reuse of code. Some fuctios just carried out a task, while others retured a value from some computatio, which could the be used i our program. You have see how argumets eable fuctios to use differet values at differet times, thus extedig their flexibility ad reusability. 48

49 Evets ad evet hadlers 4 Evets ad evet hadlers This sectio aims to: itroduce the idea of visual compoets ad the evet-drive programmig model; show how we ca add simple GUI compoets to a JavaScript program; show how fuctios allow us to create code which provides appropriate actios whe users iteract with those compoets. 4.1 Graphical user iterfaces I the early days of computig the majority of people who used computers were scietifically ad techologically orieted ad motivated. They did t worry about how difficult the machies were to use, sice what they wated was to access the amazig computatioal power these ew machies could provide. Over time, the rage of people who have to iteract with computers o a regular basis has steadily wideed. As a result, the average computer user s level of techical uderstadig ad the extet to which they are prepared to cope with ufriedly software applicatios has decreased. We are o loger i a situatio where it is reasoable to expect everyoe to remember complex sequeces of key combiatios i order to use the software applicatios available o their machies. Probably the most sigificat move forward i computer usability i the last 50 years is the itroductio of the graphical user iterface or GUI which has trasformed our iteractio with PCs from a text-based, commad-lie iterface to oe where there are various visual compoets o the scree with which we ca iteract i a more ituitive maer. Iterfaces As recetly as the 1970s ad early 1980s, people used to iteract with a remote computer usig a teletype. A user would type i oe commad a sigle lie of text at a time, the wait for the computer s respose to be prited o a liked priter before typig i the ext commad. The operatig systems of early PCs took a similar approach. WIMP iterfaces widows, icos, mice ad pull-dow meus were origially developed by researchers at Xerox Palo Alto Research Cetre ad take up o a commercial basis by the 49

50 Uit 8 Programs ad data producers of Atari ad Apple computers. Predomiatly text-based eviromets were replaced by the visual eviromets which are ow uiversal ad which most of us fid easier to use. Figure 4.1 A teletype termial ad liked priter We look at ways i which the overall usability of computer-based applicatios has bee improved i Uits 12 ad 13, where huma computer iteractio (HCI) is cosidered i some detail. Most of us are familiar with moder widows-based operatig systems, ad regularly use visual compoets (sometimes referred to as GUI widgets) such as buttos, text boxes, checkboxes, drop-dow meus, sliders, ad so o whe we ru applicatios. widow poiter meu icos Figure 4.2 A typical GUI highlightig the mai elemets 50

51 Evets ad evet hadlers 4.2 Evets The itroductio of GUIs has chaged how programmers eed to thik about developig software, at least at the user iterface level. They are o loger i the situatio where they have to write oe large program i which all the sequecig of activities has to be built ito their code i advace. Istead they have to thik about how their program should react to the various ways a user might activate the visual compoet(s). We talk about a evet-drive model i which the computer registers the occurrece of a evet wheever the user does somethig which chages the state of oe of the compoets o the scree For example, a evet might be a click o a butto, or the movemet of the cursor over a image, or a attempt to drag ad drop a ico to a ew positio o the scree. For each of these evets, the programmer has to provide code that will carry out the actios required as a result of the evet havig occurred. We call these pieces of code evet hadlers. Each oe eeds to be attached i some way to the compoet for which the evet occurred ad so i geeral GUI programmig cosists of a relatively large umber of relatively small pieces of code. As user iterfaces have developed, programmig laguages have had to follow suit, ad programmers have had to lear ew skills. Moder programmig laguages, ad the developmet eviromets withi which they are used, have bee exteded to iclude most of the features that programmers eed i order to build products with graphical user iterfaces, quickly ad efficietly. 4.3 Addig GUI compoets to programs To add GUI compoets to JavaScript programs, we eed to iclude the details of the required visual compoets i the body of our HTML code documet. As you leared i Uit 7, every browser widow has a documet associated with it, to which the output from programs is directed. I tur, each documet ca have a umber of forms associated with it, ad each form ca have a umber of GUI widgets (such as buttos ad text boxes) associated with it. You ca see how these various features are related i the compoet hierarchy show i Figure 4.3. These GUI widgets are kow as elemets i HTML pages. Fially, both forms ad GUI elemets have a umber of properties, called attributes, which specify thigs such as their ame, appearace ad effect. To use the various graphical compoets i programs we eed to declare them to the system (as we do with variables) ad assig values to ay relevat attributes. As GUI elemets must be associated with a form, the procedure for usig them ivolves the followig steps. 51

52 Uit 8 Programs ad data widow documet form1 oe or more forms each cotaiig oe or more GUI widgets butto 1 butto 2 text box form2 butto 3 Figure 4.3 Structure of a browser widow displayig GUI widgets Whe you ru your program, you will ot be able to see the form. Create a form o which you ca place the elemets, by icludig the <FORM> ad </FORM> tags. (All defiitios associated with the form will the be icluded betwee these tags.) Assig a value to the NAME attribute of the form, so that it ca be referred to i the code. Create each elemet which receives iput from a user (such as a butto), usig the <INPUT> tag. (This tag does t eed a ed tag.) Set relevat attributes of the iput elemet, for example: TYPE (e.g. butto, checkbox); VALUE (which i the case of a butto is the text displayed o the butto its label); ONCLICK (the attribute of a butto which specifies the actio to be take whe it s clicked). The code to carry out the actio is called a evet hadler. Here is a example of the code for creatig a form with a butto. <HEAD> <TITLE>Program_8.4.1</TITLE> <SCRIPT> // JavaScript code will go i here </SCRIPT> </HEAD> <BODY> <FORM NAME = "greetig"> <INPUT TYPE = "butto" VALUE = "Press Me" ONCLICK = "widow.cofirm('do you realise you just pressed the butto?')" > </FORM> 52

53 Evets ad evet hadlers Note that widow.cofirm() displays a dialogue box with two buttos, OK ad cacel. If the OK butto is clicked, it returs the Boolea value true; if the cacel butto is clicked, it returs the Boolea value false. A ote o formattig We have cotiued the covetio itroduced i Uit 7 of typig the various HTML reserved words, such as NAME ad VALUE, i upper-case letters to emphasise that they are ot JavaScript. Also ote that the values assiged to them are eclosed i double quotes, agai to distiguish them from JavaScript strigs. I this example, we have set attributes as follows: the NAME attribute of the form to "greetig"; the TYPE attribute of the elemet to "butto"; the VALUE attribute of the butto (its label) to "Press Me". the ONCLICK attribute of the butto (the actio to be take whe it is clicked) is assiged the code eeded to produce a cofirm box with the questio Do you realise you just pressed the butto?. This simple example cotais othig i the head of the file except a commet, but i later examples we will be puttig JavaScript code betwee the <SCRIPT> ad </SCRIPT> tags as we have doe i our programs throughout Uits 7 ad 8. A cofirm box is a dialogue box similar to a promptbox,but i which the user is give oly two optios, to click OK or to click Cacel. Like prompt(), cofirm() is a method associated with the Widow object. ACTIVITY 4.1 Program_8.4.1 cotais the program described above. Ru it a couple of times ad click o the butto as requested. Do you otice aythig surprisig about the butto? Discussio You should see somethig like Figure 4.4. Figure 4.4 Program_8.4.1 screeshot Did you otice that the program does ot die oce you have clicked the butto ad respoded to the cofirm box. Oce lauched the program sits there waitig to respod to ay umber of clicks from a user util its executio is explicitly halted by closig the browser widow. This is typical 53

54 Uit 8 Programs ad data of evet-hadlig programs, which are desiged to respod to user iput wheever it might occur. You could go off ad read your or edit a Word documet, ad the come back ad click the butto agai as with may applicatios you are accustomed to usig. ACTIVITY 4.2 Aother type of dialogue box provided by the widow object is the alert box, which, as its ame implies, is desiged to display a warig message (though it could be used to display ay text). It is the simplest of the three dialogue boxes you have met, as the oly possible respose from the user is to click the OK butto i order to ackowledge that they have read the message. It is produced by the alert() method of the Widow object ad takes a sigle strig argumet, the text for the message to be displayed. The file Activity_8.4.2 cotais a copy of Program_ Modify the code i this file so that i respose to the butto beig clicked it displays a alert box with the text Hello world! istead of the cofirm box. Ru your program to check that it works as you expect. Discussio All that eeded chagig was the value of the ONCLICK attribute, which should ow read as follows. ONCLICK = "widow.alert('hello world!')" The output from your program should have bee similar to that show i Figure 4.5. Figure 4.5 Solutio_8.4.2 screeshot A workig program is available as Solutio_ Hello world! We have icluded this Hello world! program because it has somethig of a cult status i the field of programmig! Whe programmig i a ew laguage or eviromet a programmer s first challege is usually to see whether they ca get a program to write out aythig, ad the use of the phrase 'Hello world!' has become somethig of a traditio i this cotext. 54

55 Evets ad evet hadlers Addig a text box to the form Dialogue boxes are ot always appropriate for output, sice oce the box is displayed, the program ca t do aythig else util the user dismisses it. What if we eed to keep the output visible, while cotiuig to iteract with the program, e.g. by pressig aother butto? Oe way of achievig this is to add aother compoet to our form a text box, which we ca use either to obtai iput from the user or to display output, or both. As with the butto, we eed to specify: the TYPE attribute of our ew elemet, which for a text box is "text"; its VALUE attribute, which i the case of a text box is the text we wat displayed i the box; a NAME for the elemet, so that we ca specify i the code where ay iput is to come from or where ay output is to be displayed. All this ca be doe with a HTML statemet such as: <INPUT TYPE = "text" NAME = "respose" VALUE = ''> SAQ 4.1 What do you thik will iitially be displayed i the text box defied above? Remember we have adopted the covetio of eclosig attribute values i double quotes except for simple strigs such as those appearig i text boxes. Aswer to SAQ The output text is specified by the VALUE attribute ad so, as the empty strig is specified, the box will ot iitially cotai ay text. You may be a little puzzled by the use of the <INPUT> tag to specify this elemet, as we are curretly usig it for output. HTML uses this tag for all elemets that ca be used for both iput ad output. If the text box declaratio is placed immediately after the existig butto declaratio, the the text box will appear o the form ext to the butto. To output aythig to the text box durig program executio the value of the text elemet must be chaged. How do we do that? You will remember that we origially put a form amed "greetig" ito our documet; the we put a text box amed "respose" o the form. So employig the usual dot otatio, we ca assig a strig, such as 'Hello world' to the VALUE attribute as show i Figure 4.6. Documet object form amed greetig text box amed respose value of text box strig to be assiged documet.greetig.respose.value = 'Hello world!' Figure 4.6 JavaScript statemet to assig the strig 'Hello world!' to a text box value The statemet is best uderstood by readig it from right to left: the strig 'Hello world!' is to be assiged to the value of the text box amed "respose" o the form amed "greetig" which belogs to our curret Documet object. 55

56 Uit 8 Programs ad data Fially, i order for the strig to be output i respose to a butto click, we must assig this statemet to the ONCLICK attribute of the butto. Puttig it all together, we have the followig program. <HTML> <HEAD> <TITLE>Program_8.4.3</TITLE> <SCRIPT> /* JavaScript code will go i here */ </SCRIPT> </HEAD> <BODY> <!-- HTML code to create a form --> <FORM NAME = "greetig"> <!-- HTML code to create a butto o the form --> <INPUT TYPE = "butto" VALUE = "Press Me" ONCLICK = "documet.greetig.respose.value = 'Hello world!'"> <!-- HTML code to create a text box o the form --> <INPUT TYPE = "text" NAME = "respose" VALUE = ''> </FORM> </BODY> </HTML> Note the use of the <!-- ad -- > tags to idicate commets i the HTML code, rather tha the // or /* ad */ used i JavaScript. If JavaScript commets were used i the HTML code, they would be displayed i the output! You will fid a copy of this code as Program_ ACTIVITY 4.3 The file Activity_8.4.3 cotais a copy of Program_ Ru this program i order to see its output the modify the program as follows. (a) Chage the label of the first butto to: Hello. (b) Chage the message which appears i respose to clickig the butto to: Hello emptiess! (c) Add a secod butto, with label Goodbye, ad a secod text box, with the ame farewell. The cotet of the text box should be iitialised to the empty strig, but whe the butto is clicked it should display 'Goodbye to romace'. 56

57 Evets ad evet hadlers Whe you ru your program ad click the Hello ad Goodbye buttos you should see somethig similar to Figure 4.7. Figure 4.7 Expected browser widow Hit I Program_8.4.3 the butto ad the text box were placed ext to each other o the form because they were successive declaratios i our code. By usig the <BR> tag to move to a ew lie, you ca place elemets udereath each other, as we have doe with our secod butto ad text box. Discussio (a) To chage the butto label to Hello, you simply eed to chage its VALUE attribute to "Hello". (b) The value assiged to the ONCLICK attribute should be chaged to "documet.greetig.respose.value = 'Hello emptiess!'" (c) The declaratio for the secod butto would be as follows: <INPUT TYPE = "butto" VALUE = "Goodbye" ONCLICK = "documet.greetig.farewell.value = 'Goodbye to romace'"> The declaratio for the secod text box would be as follows: <INPUT TYPE = "text" NAME = "farewell" VALUE = ''> You will fid our complete solutio as Solutio_ There may be circumstaces whe we wat a butto press to cause more tha oe actio. For example, suppose that i respose to a sigle click of a butto with the label Studet Details, we wated a studet s ame, persoal idetifier ad course code to appear i differet text boxes (called ame, idetifier ad course) o a form called details. Here are the relevat declaratios. 57

58 Uit 8 Programs ad data <!-- HTML code to create the butto --> <INPUT TYPE = "butto" VALUE = "Studet Details" ONCLICK = "documet.details.ame.value = 'Josie Bloggs'; documet.details.idetifier.value = 'P '; documet.details.course.value = 'M150'"> <BR> <!-- HTML code to create three text boxes o the form --> <INPUT TYPE = "text" NAME = "ame" VALUE = ''> <INPUT TYPE = "text" NAME = "idetifier" VALUE = ''> <INPUT TYPE = "text" NAME = "course" VALUE = ''> You ca see that we ve assiged a sequece of three program statemets to the ONCLICK attribute. Whe a browser reads (parses) this page, it will pass all the code i quotes to the JavaScript iterpreter. The full code for this program is available as Program_ Usig fuctios as evet hadlers You may have cocluded from the example above that thigs are goig to get rather difficult to follow if we wat to do aythig at all complicated whe a butto is pressed. Just addig more ad more lies of code after the ONCLICK reserved word i the butto declaratio is goig to be hard to maage, ad to uderstad. What we really eed as a evet hadler is a call to a fuctio whose ame gives us a idea of what should happe whe it is ivoked. We ca the put the details of the correspodig fuctio defiitio somewhere more coveiet. As with all the JavaScript code we have writte so far, the fuctio defiitios for the various evet hadlers eed to go betwee <SCRIPT> ad </SCRIPT> i the HEAD of the HTML page. I our example of Studet Details we ca defie a fuctio called, say, displaydetails(), ad chage the butto declaratio i the BODY of the file to: <INPUT TYPE = "butto" VALUE = "Studet Details" ONCLICK = "displaydetails()" > EXERCISE 4.1 Write dow the defiitio of a fuctio called displaydetails() which carries out the three actios assiged to the ONCLICK attribute i the code for Program_ Remember that whe defiig a fuctio you must iclude a fuctio header ad a body. 58

59 Evets ad evet hadlers Discussio The required fuctio defiitio is as follows. fuctio displaydetails() documet.details.ame.value = 'Josie Bloggs'; documet.details.idetifier.value = 'P '; documet.details.course.value = 'M150' Did you remember to iclude the fuctio reserved word? This fuctio has o argumets ad o retur value. ACTIVITY 4.4 The file Activity_8.4.4 cotais a copy of the code for Program_ Ope this file i Notepad ad make sure you uderstad the code to create the form, the butto ad the text boxes. The modify the code so as to use the fuctio you defied i Exercise 4.1. You will eed to: add your JavaScript fuctio defiitio betwee the <SCRIPT> ad </SCRIPT> tags; replace the three lies of code assiged to the ONCLICK attribute of the butto by a sigle fuctio call. Save your program ad ru it. Discussio You should have foud that your program behaves idetically to Program_ Our full solutio is available as Solutio_ SAQ 4.2 Ca you thik of aother reaso for usig fuctios as evet hadlers? Aswer to SAQ Aother advatage of usig fuctios as evet hadlers is that the same fuctio ca potetially be reused i a umber of differet situatios. 59

60 Uit 8 Programs ad data 4.5 Addig user iput to a GUI We metioed i Subsectio 4.3 that a text box ca be used for both iput ad output, although so far we have oly used it for displayig output. Whe a text box is used for iput, the user eeds to be told that they must eter somethig which will the become the curret VALUE of the text box, ad ca be accessed for use elsewhere i the program. Suppose we wat to modify the program which displayed Hello world! i a text box (Program_8.4.3) so that it asks the user for their ame, ad the greets them by ame. Istead of the geeral greetig, 'Hello world!' we would issue the persoalised greetig of, say, 'hello Staley'. Some text, such as Please type i your ame has to be placed ext to the box. This is doe by icludig the required text i the HTML file, at the poit where we wat it to be displayed. So that iput is ot cofused with output, we will separate the differet aspects of our program, by placig a secod text box o the form called username, ito which we ask the user to type their ame. We ca do this by addig the followig statemets to the HTML documet. Please type i your ame <BR> <INPUT TYPE = "text" NAME = "username" VALUE = ''> <BR> SAQ 4.3 How ca the program access the text typed i by the user? Aswer to SAQ Remember that the text displayed i a text box is assiged to its VALUE attribute. So oce the user has etered some text i the box, it ca be accessed as the value of the text box "username" o the form "greetig" associated with our documet, that is: documet.greetig.username.value We ow eed to modify the code which hadles the butto click evet. I Program_8.4.3 the result of pressig the butto was to display 'Hello world!' i the text box called "respose". We ow wat the display to be 'hello', cocateated with whatever the user typed i. We ca set the VALUE attribute of the text box to this ew strig as follows. documet.greetig.respose.value = 'hello ' + documet.greetig.username.value Our complete code for this program is available as Program_ If you ru it ad eter your ame i the top text box, ad press the Now Press Me butto, the hello followed by your ame will appear i the secod box; see Figure 4.8 for a example. 60

61 Evets ad evet hadlers Figure 4.8 Program_8.4.5 screeshot SAQ 4.4 What would happe if you clicked the butto without havig etered aythig i the text box? Aswer to SAQ You would just get the message 'hello' (which would be followed by the empty strig). EXERCISE 4.2 How could the program detect that there is othig i the box ad war the user accordigly? Discussio We could use a if statemet with a suitable coditio to test whether the strig assiged to the VALUE attribute of the box is equal to the empty strig. If it is the we could use a alert box to issue a warig message such as Do't forget to eter your ame before pressig the butto. Here is the code for displayig the box: widow.alert ('Do\'t forget to eter your ame before pressig the butto') You may remember from Uit 7 that i order to use a apostrophe i a strig you eed to precede it by a escape character, a back slash (\). ACTIVITY 4.5 The file Activity_8.4.5 cotais a slightly modified versio of Program_ Our modified program behaves i exactly the same way as Program_8.4.5, but we have modified the code to itroduce a fuctio called greetuserbyname(). Ope the file Activity_8.4.5 i Notepad ad study the code. We have icluded commets to explai our modificatios. 61

62 Uit 8 Programs ad data Now modify the code of the evet hadler (the greetuserbyname() fuctio) so that it checks whether the user has etered aythig before pressig the butto. If ot, the program should war them accordigly, usig a alert box; otherwise the program should output a greetig as before. Hits Here is the required algorithm i structured Eglish. if iput textbox is empty the war the user of this fact else greet the user by ame ed if Remember that the JavaScript operator for comparig two values to test whether they are equal is ==. Test your program by ruig it both with ad without somethig typed ito the iput box. Discussio Here is our code for the modified fuctio. Yours may have a differet warig message. if (documet.greetig.username.value == '') widow.alert ('Do\'t forget to eter your ame before pressig the butto') else documet.greetig.respose.value = 'hello ' + documet.greetig.username.value Note that i the first lie of code the two quotatio marks are adjacet: they do ot have a space betwee them. A empty strig is ot the same as a strig with a sigle space i it. Did you remember to use the escape character before the apostrophe i Do t? Our complete workig program for this activity is available as Solutio_

63 Evets ad evet hadlers 4.6 A uits coversio program This sectio eds with a slightly more challegig activity, which brigs together several of the programmig cocepts you have leared so far. ACTIVITY 4.6 I Activities 3.4(b) ad 3.5, you wrote the followig fuctio to covert litres to gallos ad retur the result to two decimal places. fuctio togallos(umberoflitres) retur twodps(umberoflitres * ) I this activity you will use this fuctio, together with what you have just bee learig about buttos ad text boxes, to write a slightly more iteractive coversio program. The user will be asked to type i a value i litres ad, o clickig a butto labelled Covert, will be provided with the equivalet umber of gallos. A simple iterface for the program is show i Figure 4.9. Figure 4.9 Iterface for the litres to gallos coversio program If you feel cofidet with the programmig so far, you may wat to try this activity o your ow. If ot, you ca follow the guided steps below, which iclude Exercises 4.3 ad 4.4. We have provided you with the file Activity_8.4.6 which idicates where you should add the code for the various parts of the program. EXERCISE 4.3 Write dow the declaratios eeded to produce the butto, text boxes ad text show i Figure 4.9. Remember that you will also eed to create a form o which to place them. (You should leave the ONCLICK attribute of the butto blak for the time beig, as this will require some further discussio.) 63

64 Uit 8 Programs ad data Discussio There was quite a lot to remember here. You first eeded to set up the form, called somethig meaigful like coverter, ad the to add declaratios for the various compoets eeded. Here is our code for this part of the program. (You may have chose differet ames ad differetly worded text.) <!-- declaratio for form --> <FORM NAME = "coverter"> <!-- text idicatig to the user that they should eter a umber of litres --> please eter value i litres <BR> <!-- declaratio for text box to receive iput i litres --> <INPUT TYPE = "text" NAME = "litres" VALUE = '' > <BR> <!-- declaratio for the butto value of ONCLICK attribute still to be added --> <INPUT TYPE = "butto" VALUE = "Covert" ONCLICK = "<!-- to be added -->"> <BR> <!-- label for secod text box --> equivalet i gallos is <BR> <!-- declaratio for text box to output value i gallos --> <INPUT TYPE = "text" NAME = "gallos" VALUE = ''> <BR> Next you eed to thik about what happes whe the butto is clicked. The user will (hopefully!) have typed a umber of litres ito the first text box, amed litres. You eed to: call the togallos() fuctio with this umber of litres as argumet; assig the retur value from the fuctio to the VALUE attribute of the secod text box (called gallos). EXERCISE 4.4 Write dow the code that will be assiged to the ONCLICK attribute of the butto. 64

65 Evets ad evet hadlers The required code is as follows. Discussio documet.coverter.gallos.value = togallos(documet.coverter.litres.value) Fially, you eed to add all the code to the program. Fuctio defiitios eed to go betwee <SCRIPT> ad </SCRIPT> i the head of the HTML code. Remember to iclude the code for the twodps() fuctio as well as the togallos() fuctio, because twodps() is eeded by togallos(). You ca copy ad paste the code for both fuctios from Solutio_ Code for the form, butto, prompts ad text boxes eeds to go i the BODY of the HTML code. If you have ot already doe so, ope Activity_8.4.6 ad add the various sectios of code i the places idicated by our commets. Ru your program ad test it with a variety of iputs. We are ow i a positio to provide a discussio of Activity 4.6. Discussio Here is our complete program, which is available as Solutio_ <HTML> <HEAD> <TITLE>Solutio_8.4.6</TITLE> <SCRIPT> fuctio twodps(aynumber) retur Math.roud (100 * aynumber) / 100 fuctio togallos(umberoflitres) retur twodps(umberoflitres * ) </SCRIPT> </HEAD> <BODY> <!-- declaratio for form --> <FORM NAME = "coverter"> <!-- text idicatig to the user that they should eter a umber of litres --> please eter value i litres <BR> 65

66 Uit 8 Programs ad data <!-- declaratio for text box to receive iput i litres --> <INPUT TYPE = "text" NAME = "litres" VALUE = ''> <BR> <!-- declaratio for the butto value of ONCLICK assigs the umber of gallos to the VALUE attribute of the "gallos" text box --> <INPUT TYPE = "butto" VALUE = "Covert" ONCLICK = "documet.coverter.gallos.value = togallos(documet.coverter.litres.value)"> <BR> <!-- label for secod text box --> equivalet i gallos is <BR> <!-- declaratio for text box to output value i gallos --> <INPUT TYPE = "text" NAME = "gallos" VALUE = ''> <BR> </FORM> </BODY> </HTML> You may thik that the code assiged to ONCLICK is still rather messy. We could iclude this code i a ew evet-hadlig fuctio called somethig like covert() ad add this fuctio to the JavaScript sectio of the program If you wated to war the user that they have failed to eter a value before pressig the Covert butto you could iclude a copy of the code that was used to do this i Activity 4.5. You should be startig to realise that almost everythig that you have doe previously is i some sese reusable. Whe you work o programmig tasks, you eed to be cosciously lookig out for patters that might be useful i aother cotext, ad of course rememberig where you put ay code that you may wat to copy i future programs! 4.7 Summary I this sectio we itroduced you to the ways i which you ca improve user iteractio with your programs by icludig visual compoets, such as buttos ad text boxes. You saw that we ca write fuctios cotaiig code for the evet hadlers which provide the appropriate respose to user actios such as clickig o a butto. Fially we reiforced the idea of code reuse by idetifyig situatios i which code writte i this ad earlier sectios could be icorporated ito ew programs. 66

67 Strigs 5 Strigs This sectio aims to: exted the kowledge of Strig objects that you gaied i Uit 7; use the built-i JavaScript Strig methods to develop a collectio of your ow strig-processig fuctios, cocetratig iitially o processig strigs with sigle characters; use the strig-processig fuctios we have developed i order to implemet a password-checkig program. You have already met the cocept of a strig i may places i this course, but we will start this sectio with a brief revisio. As far as JavaScript is cocered a strig is ay sequece of letters, digits, puctuatio ad other special characters which eed to be treated as a sigle etity. Whe sigle characters are processed i JavaScript, they are treated as strigs oe character log. JavaScript Strig objects provide a collectio of basic methods to assist us with strig processig. We will look briefly at some of these methods, before goig o to use them as the basis for developig strig-processig fuctios of our ow. 5.1 Strig processig Whe strigs are processed, it may be ecessary to access idividual characters ad maipulate them. I this sese, you ca thik of a strig as beig similar to a array of characters. You leared i Uit 7 that Strig objects, like Array objects, have a legth property which returs the umber of characters cotaied i the strig. You also used the charat()method which returs the sigle character at a specified positio i the strig, usig the same zero-based idexig that you met whe lookig at arrays. Thus, if the variable mystrig curretly has the value 'Hello world!' the mystrig.legth will retur the value 12, sice spaces ad exclamatio marks also cout as separate characters, ad mystrig.charat(4) will retur the value 'o', a strig cosistig of the fifth character i the strig. If a argumet for charat() that falls outside the rage 0 to mystrig.legth 1 is used, the a empty strig will be retured. 67

68 Uit 8 Programs ad data Aother useful method is the idexof() method, which returs the positio of the begiig of the first occurrece of ay specified substrig withi the give strig. If the substrig is ot preset i the give strig the it returs 1. For example, if mystrig curretly has the value 'Hello world!', mystrig.idexof('hell') returs 0 mystrig.idexof('world') returs 6 mystrig.idexof('r') returs 8 mystrig.idexof('low') returs 1 (as mystrig cotais the substrig 'lo w', but ot 'low'). Remember that we are usig zero-based idexig ad that spaces also cout as characters. mystrig mystrig.charat(4) is 'o' 0 H 1 e 2 l 3 l 4 o 5 6 w 7 o 8 r l d! mystrig.legth is 12 mystrig.idexof('r') is 8 Figure 5.1 mystrig as 'Hello world!' showig results of Strig properties ad methods The built-i Strig methods we have looked at are fairly basic. I the followig sectios of the uit we will use them to costruct some slightly more complex strig-processig fuctios, cocetratig iitially o maipulatig strigs with a sigle character. 5.2 Some character-processig fuctios What ay programmig laguage provides as built-i facilities, o matter how powerful these may be, is oly a startig poit, a set of basic tools ad buildig blocks. Most of the problems we meet will require us to assemble these basic blocks ito larger structures of our ow. We start writig our ow strig-processig fuctios by developig a few operatios o sigle character strigs, as these fuctios will be useful whe we eed to take loger strigs apart ad look at the idividual characters. I Uit 7, we discussed how strigs, or ay other items that ca be ordered, ca be compared usig the compariso operators (e.g. <, <=, >, >=). You leared, for example, that: '3' < '5', 'a' < 'c' ad 'B' < 'Z' all evaluate to true. 68

69 Strigs Testig whether a character is a digit To test whether a give character is a digit, we eed to check whether it is i the character rage '0' to '9', i.e. whether the character is greater tha or equal to the character '0' ad, at the same time, is less tha or equal to the character '9'. The ability to compare strigs arises from the fact that characters are stored i the computer as umeric codes, ad that groups of related characters are represeted by cotiguous sequeces of umbers. You leared i Uit 3 that character codes i moder computers are ormally represeted by the Uicode stadard. EXERCISE 5.1 Suppose acharacter is a variable whose value is a strig cosistig of a sigle character. (a) Write dow a coditioal expressio i JavaScript which checks whether acharacter is greater tha or equal to the character '0'. (b) Write dow a coditioal expressio i JavaScript which checks whether acharacter is less tha or equal to the character '9'. The correct expressios are: (a) acharacter >= '0' (b) acharacter <= '9' Discussio Puttig these two expressios together, we kow that acharacter is a umeric character if (acharacter >= '0') && (acharacter <= '9') We ca geeralise this coditio to apply to ay sigle character strig by defiig a fuctio amed isnumeric() which takes a strig with a sigle character as its argumet ad returs a Boolea result, as follows. fuctio isnumeric(acharacter) retur (acharacter >= '0') && (acharacter <= '9') You may be a bit puzzled by the fact that we do ot explicitly retur true or false from this fuctio. We could have writte the body of the fuctio as: if ((acharacter >= '0') && (acharacter <= '9')) retur true1 else retur false However, as the expressio (acharacter >= '0') && (acharacter <= '9') evaluates to true or false, we ca retur its value directly. You used AND, OR ad NOT i Uit 6, ad met the JavaScript operators &&, ad! for implemetig them i Uit 7. 69

70 Uit 8 Programs ad data I the Uicode sequece the uppercase ad lower-case letters are i two sequeces separated by some oalphabetic characters. Testig whether a character is alphabetic Testig whether a give character is alphabetic is slightly more complex, as we eed to check two separate sets of cotiguous codes, oe for the uppercase characters ad oe for the lower-case characters We might decide to make a virtue out of this mior difficulty by providig two separate fuctios for checkig whether the character is upper case ad whether it is lower case, respectively, o the basis that there are times whe each of these checks could be useful i its ow right. Havig doe this, we ca the combie these two fuctios ito aother fuctio that checks whether the character is alphabetic, regardless of its case. Followig the approach that we took for isnumeric() we ca write the followig fuctio to test whether a character is lower case: fuctio islowercase(acharacter) retur (acharacter >= 'a') && (acharacter <= 'z') EXERCISE 5.2 Write dow a similar defiitio for the fuctio isuppercase(). Discussio We eed to replace the lower-case characters 'a' ad 'z'with their uppercase equivalets 'A' ad 'Z' ad chage the ame of the fuctio, so we write: fuctio isuppercase(acharacter) retur (acharacter >= 'A') && (acharacter <= 'Z') We ca ow combie these two fuctios ito our isalpha() fuctio, sice a alphabetic character is oe which is either upper case or lower case. fuctio isalpha(acharacter) retur (isuppercase(acharacter) islowercase(acharacter)) Testig whether a character is alphaumeric Fially, i this curret group of fuctios, we ca combie the isalpha() ad isnumeric() fuctios ito a sigle fuctio amed isalphanumeric(). This will be useful i Subsectio 5.3, whe we wat to check that all the characters i a strig are legal alphaumeric characters, i.e. either alphabetic or umeric characters. We defie this fuctio as: fuctio isalphanumeric(acharacter) retur (isalpha(acharacter) isnumeric(acharacter)) 70

71 Strigs Cosider the simplicity of this last fuctio, ad compare it with the complexity that would be ivolved if all the logic for each of the separate checks were put ito a sigle coditio. You should appreciate that the process of buildig a fuctio out of several smaller fuctios, each doig a simple task, improves the uderlyig structure of the code ad makes it more uderstadable. ACTIVITY 5.1 Program_8.5.1 demostrates the way each of these fuctios behaves. Ru the program ad try out each fuctio with various iput characters by pressig the relevat buttos that appear o the form, as show i Figure 5.2. You should cosider the rage of characters that you eed to try i order to be satisfied that all the fuctios work correctly, bearig i mid what you leared about testig i Uit 7. Discussio At the very least you would eed to test each fuctio usig a typical umeric character like 6, a typical upper-case character like M ad a typical lower-case character like h, ad you should also check oe or more characters which do ot fall i to ay of these categories such as or >. If you were worried about the boudary coditios you would check the eds of the various rages, such as 0 ad 9, A ad Z. You might also wish to look at what happes to the characters just outside the boudaries. If you were to cosult a table of Uicode characters you would fid, for example, is the character before A ad [ is the character followig Z. There are several features i the GUI code for Program_8.5.1 that were ot covered i Sectio 4. We do ot expect you to lear these, but have icluded some explaatory commets i the source file i case you are iterested. Figure 5.2 Output from Program_ A password-checkig program We complete this sectio by developig a more complex strig-processig program, which makes use of character-processig fuctios to check the validity of a password chose by the user. We do ot expect you to be able to write a complete program of this complexity for yourself, but you should 71

Computers and Scientific Thinking

Computers and Scientific Thinking Computers ad Scietific Thikig David Reed, Creighto Uiversity Chapter 15 JavaScript Strigs 1 Strigs as Objects so far, your iteractive Web pages have maipulated strigs i simple ways use text box to iput

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Pytho Programmig: A Itroductio to Computer Sciece Chapter 1 Computers ad Programs 1 Objectives To uderstad the respective roles of hardware ad software i a computig system. To lear what computer scietists

More information

. Written in factored form it is easy to see that the roots are 2, 2, i,

. Written in factored form it is easy to see that the roots are 2, 2, i, CMPS A Itroductio to Programmig Programmig Assigmet 4 I this assigmet you will write a java program that determies the real roots of a polyomial that lie withi a specified rage. Recall that the roots (or

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Pytho Programmig: A Itroductio to Computer Sciece Chapter 6 Defiig Fuctios Pytho Programmig, 2/e 1 Objectives To uderstad why programmers divide programs up ito sets of cooperatig fuctios. To be able to

More information

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design College of Computer ad Iformatio Scieces Departmet of Computer Sciece CSC 220: Computer Orgaizatio Uit 11 Basic Computer Orgaizatio ad Desig 1 For the rest of the semester, we ll focus o computer architecture:

More information

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis Itro to Algorithm Aalysis Aalysis Metrics Slides. Table of Cotets. Aalysis Metrics 3. Exact Aalysis Rules 4. Simple Summatio 5. Summatio Formulas 6. Order of Magitude 7. Big-O otatio 8. Big-O Theorems

More information

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June CS 1313 010: Programmig for No-Majors, Summer 2007 Programmig Project #3: Two Little Calculatios Due by 12:00pm (oo) Wedesday Jue 27 2007 This third assigmet will give you experiece writig programs that

More information

One advantage that SONAR has over any other music-sequencing product I ve worked

One advantage that SONAR has over any other music-sequencing product I ve worked *gajedra* D:/Thomso_Learig_Projects/Garrigus_163132/z_productio/z_3B2_3D_files/Garrigus_163132_ch17.3d, 14/11/08/16:26:39, 16:26, page: 647 17 CAL 101 Oe advatage that SONAR has over ay other music-sequecig

More information

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming Lecture Notes 6 Itroductio to algorithm aalysis CSS 501 Data Structures ad Object-Orieted Programmig Readig for this lecture: Carrao, Chapter 10 To be covered i this lecture: Itroductio to algorithm aalysis

More information

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence _9.qxd // : AM Page Chapter 9 Sequeces, Series, ad Probability 9. Sequeces ad Series What you should lear Use sequece otatio to write the terms of sequeces. Use factorial otatio. Use summatio otatio to

More information

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 4 Procedural Abstractio ad Fuctios That Retur a Value Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 4.1 Top-Dow Desig 4.2 Predefied Fuctios 4.3 Programmer-Defied Fuctios 4.4

More information

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 1 Itroductio to Computers ad C++ Programmig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 1.1 Computer Systems 1.2 Programmig ad Problem Solvig 1.3 Itroductio to C++ 1.4 Testig

More information

How do we evaluate algorithms?

How do we evaluate algorithms? F2 Readig referece: chapter 2 + slides Algorithm complexity Big O ad big Ω To calculate ruig time Aalysis of recursive Algorithms Next time: Litterature: slides mostly The first Algorithm desig methods:

More information

Ones Assignment Method for Solving Traveling Salesman Problem

Ones Assignment Method for Solving Traveling Salesman Problem Joural of mathematics ad computer sciece 0 (0), 58-65 Oes Assigmet Method for Solvig Travelig Salesma Problem Hadi Basirzadeh Departmet of Mathematics, Shahid Chamra Uiversity, Ahvaz, Ira Article history:

More information

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 8 Strigs ad Vectors Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Slide 8-3 8.1 A Array Type for Strigs A Array Type for Strigs C-strigs ca be used to represet strigs

More information

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 11 Frieds, Overloaded Operators, ad Arrays i Classes Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Overview 11.1 Fried Fuctios 11.2 Overloadig Operators 11.3 Arrays ad Classes 11.4

More information

Elementary Educational Computer

Elementary Educational Computer Chapter 5 Elemetary Educatioal Computer. Geeral structure of the Elemetary Educatioal Computer (EEC) The EEC coforms to the 5 uits structure defied by vo Neuma's model (.) All uits are preseted i a simplified

More information

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS) CSC165H1, Witer 018 Learig Objectives By the ed of this worksheet, you will: Aalyse the ruig time of fuctios cotaiig ested loops. 1. Nested loop variatios. Each of the followig fuctios takes as iput a

More information

CMPT 125 Assignment 2 Solutions

CMPT 125 Assignment 2 Solutions CMPT 25 Assigmet 2 Solutios Questio (20 marks total) a) Let s cosider a iteger array of size 0. (0 marks, each part is 2 marks) it a[0]; I. How would you assig a poiter, called pa, to store the address

More information

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 10 Defiig Classes Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types 10.4 Itroductio to Iheritace Copyright 2015 Pearso Educatio,

More information

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 8 Strigs ad Vectors Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Copyright 2015 Pearso Educatio, Ltd..

More information

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis Overview Chapter 6 Writig a Program Bjare Stroustrup Some thoughts o software developmet The idea of a calculator Usig a grammar Expressio evaluatio Program orgaizatio www.stroustrup.com/programmig 3 Buildig

More information

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 5 Fuctios for All Subtasks Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 5.1 void Fuctios 5.2 Call-By-Referece Parameters 5.3 Usig Procedural Abstractio 5.4 Testig ad Debuggig

More information

Exercise 6 (Week 42) For the foreign students only.

Exercise 6 (Week 42) For the foreign students only. These are the last exercises of the course. Please, remember that to pass exercises, the sum of the poits gathered by solvig the questios ad attedig the exercise groups must be at least 4% ( poits) of

More information

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup   Note: Chapter 4 Computatio Bjare Stroustrup www.stroustrup.com/programmig Abstract Today, I ll preset the basics of computatio. I particular, we ll discuss expressios, how to iterate over a series of values

More information

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway. Bjare Stroustrup www.stroustrup.com/programmig Chapter 5 Errors Abstract Whe we program, we have to deal with errors. Our most basic aim is correctess, but we must deal with icomplete problem specificatios,

More information

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 2 C++ Basics Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 2.1 Variables ad Assigmets 2.2 Iput ad Output 2.3 Data Types ad Expressios 2.4 Simple Flow of Cotrol 2.5 Program

More information

1.2 Binomial Coefficients and Subsets

1.2 Binomial Coefficients and Subsets 1.2. BINOMIAL COEFFICIENTS AND SUBSETS 13 1.2 Biomial Coefficiets ad Subsets 1.2-1 The loop below is part of a program to determie the umber of triagles formed by poits i the plae. for i =1 to for j =

More information

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 9 Poiters ad Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 9.1 Poiters 9.2 Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-3

More information

Arithmetic Sequences

Arithmetic Sequences . Arithmetic Sequeces COMMON CORE Learig Stadards HSF-IF.A. HSF-BF.A.1a HSF-BF.A. HSF-LE.A. Essetial Questio How ca you use a arithmetic sequece to describe a patter? A arithmetic sequece is a ordered

More information

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19 CIS Data Structures ad Algorithms with Java Sprig 09 Stacks, Queues, ad Heaps Moday, February 8 / Tuesday, February 9 Stacks ad Queues Recall the stack ad queue ADTs (abstract data types from lecture.

More information

12-5A. Equivalent Fractions and Decimals. 1 Daily Common Core Review. Common Core. Lesson. Lesson Overview. Math Background

12-5A. Equivalent Fractions and Decimals. 1 Daily Common Core Review. Common Core. Lesson. Lesson Overview. Math Background Lesso -A Equivalet Fractios ad Decimals Commo Core Lesso Overview Domai Number ad Operatios Fractios Cluster Uderstad decimal otatio for fractios, ad compare decimal fractios. Stadards.NF. Use decimal

More information

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13 CIS Data Structures ad Algorithms with Java Sprig 08 Stacks ad Queues Moday, February / Tuesday, February Learig Goals Durig this lab, you will: Review stacks ad queues. Lear amortized ruig time aalysis

More information

The Magma Database file formats

The Magma Database file formats The Magma Database file formats Adrew Gaylard, Bret Pikey, ad Mart-Mari Breedt Johaesburg, South Africa 15th May 2006 1 Summary Magma is a ope-source object database created by Chris Muller, of Kasas City,

More information

COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Part A Datapath Design

COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Part A Datapath Design COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Iterface 5 th Editio Chapter The Processor Part A path Desig Itroductio CPU performace factors Istructio cout Determied by ISA ad compiler. CPI ad

More information

Lecture 5. Counting Sort / Radix Sort

Lecture 5. Counting Sort / Radix Sort Lecture 5. Coutig Sort / Radix Sort T. H. Corme, C. E. Leiserso ad R. L. Rivest Itroductio to Algorithms, 3rd Editio, MIT Press, 2009 Sugkyukwa Uiversity Hyuseug Choo choo@skku.edu Copyright 2000-2018

More information

CS 11 C track: lecture 1

CS 11 C track: lecture 1 CS 11 C track: lecture 1 Prelimiaries Need a CMS cluster accout http://acctreq.cms.caltech.edu/cgi-bi/request.cgi Need to kow UNIX IMSS tutorial liked from track home page Track home page: http://courses.cms.caltech.edu/courses/cs11/material

More information

Guide to Applying Online

Guide to Applying Online Guide to Applyig Olie Itroductio Respodig to requests for additioal iformatio Reportig: submittig your moitorig or ed of grat Pledges: submittig your Itroductio This guide is to help charities submit their

More information

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions: CS 604 Data Structures Midterm Sprig, 00 VIRG INIA POLYTECHNIC INSTITUTE AND STATE U T PROSI M UNI VERSI TY Istructios: Prit your ame i the space provided below. This examiatio is closed book ad closed

More information

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts CS 111 Gree: Program Desig I Lecture 27: Speed (cot.); partig thoughts By Nascarkig - Ow work, CC BY-SA 4.0, https://commos.wikimedia.org/w/idex.php?curid=38671041 Robert H. Sloa (CS) & Rachel Poretsky

More information

Code Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013

Code Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013 Code Review s Authors: Mika V. Mätylä ad Casper Lasseius Origial versio: 4 Sep, 2007 Made available olie: 24 April, 2013 This documet cotais further details of the code review defects preseted i [1]. of

More information

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions U.C. Berkeley CS170 : Algorithms Midterm 1 Solutios Lecturers: Sajam Garg ad Prasad Raghavedra Feb 1, 017 Midterm 1 Solutios 1. (4 poits) For the directed graph below, fid all the strogly coected compoets

More information

Examples and Applications of Binary Search

Examples and Applications of Binary Search Toy Gog ITEE Uiersity of Queeslad I the secod lecture last week we studied the biary search algorithm that soles the problem of determiig if a particular alue appears i a sorted list of iteger or ot. We

More information

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions CS 111: Program Desig I Lecture # 7: First Loop, Web Crawler, Fuctios Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago September 18, 2018 What will this prit? x = 5 if x == 3: prit("hi!")

More information

Location Steps and Paths

Location Steps and Paths Locatio Steps ad Paths 3 INTHIS CHAPTER Uderstadig Locatio Steps ad Paths How do locatio paths work? We took a look at locatio paths i the overview i Chapter 1, where we saw that locatio paths look much

More information

Chapter 4 The Datapath

Chapter 4 The Datapath The Ageda Chapter 4 The Datapath Based o slides McGraw-Hill Additioal material 24/25/26 Lewis/Marti Additioal material 28 Roth Additioal material 2 Taylor Additioal material 2 Farmer Tae the elemets that

More information

The isoperimetric problem on the hypercube

The isoperimetric problem on the hypercube The isoperimetric problem o the hypercube Prepared by: Steve Butler November 2, 2005 1 The isoperimetric problem We will cosider the -dimesioal hypercube Q Recall that the hypercube Q is a graph whose

More information

Lecture 1: Introduction and Strassen s Algorithm

Lecture 1: Introduction and Strassen s Algorithm 5-750: Graduate Algorithms Jauary 7, 08 Lecture : Itroductio ad Strasse s Algorithm Lecturer: Gary Miller Scribe: Robert Parker Itroductio Machie models I this class, we will primarily use the Radom Access

More information

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000. 5-23 The course that gives CM its Zip Memory Maagemet II: Dyamic Storage Allocatio Mar 6, 2000 Topics Segregated lists Buddy system Garbage collectio Mark ad Sweep Copyig eferece coutig Basic allocator

More information

TUTORIAL Create Playlist Helen Doron Course

TUTORIAL Create Playlist Helen Doron Course TUTORIAL Create Playlist Hele Doro Course TUTY Tutorial Create Playlist Hele Doro Course Writte by Serafii Giampiero (INV SRL) Revised by Raffaele Forgioe (INV SRL) Editio EN - 0 Jue 0-0, INV S.r.l. Cotact:

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe CHAPTER 18 Strategies for Query Processig Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe Itroductio DBMS techiques to process a query Scaer idetifies

More information

GE FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III

GE FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III GE2112 - FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III PROBLEM SOLVING AND OFFICE APPLICATION SOFTWARE Plaig the Computer Program Purpose Algorithm Flow Charts Pseudocode -Applicatio Software Packages-

More information

Math 3201 Notes Chapter 4: Rational Expressions & Equations

Math 3201 Notes Chapter 4: Rational Expressions & Equations Learig Goals: See p. tet.. Equivalet Ratioal Epressios ( classes) Read Goal p. 6 tet. Math 0 Notes Chapter : Ratioal Epressios & Equatios. Defie ad give a eample of a ratioal epressio. p. 6. Defie o-permissible

More information

Ch 9.3 Geometric Sequences and Series Lessons

Ch 9.3 Geometric Sequences and Series Lessons Ch 9.3 Geometric Sequeces ad Series Lessos SKILLS OBJECTIVES Recogize a geometric sequece. Fid the geeral, th term of a geometric sequece. Evaluate a fiite geometric series. Evaluate a ifiite geometric

More information

Weston Anniversary Fund

Weston Anniversary Fund Westo Olie Applicatio Guide 2018 1 This guide is desiged to help charities applyig to the Westo to use our olie applicatio form. The Westo is ope to applicatios from 5th Jauary 2018 ad closes o 30th Jue

More information

In this chapter, you learn the concepts and terminology of databases and

In this chapter, you learn the concepts and terminology of databases and A Itroductio to Database Developmet I this chapter, you lear the cocepts ad termiology of databases ad how to desig the tables that your forms ad reports will use. Fially, you build the actual tables used

More information

FURTHER INTEGRATION TECHNIQUES (TRIG, LOG, EXP FUNCTIONS)

FURTHER INTEGRATION TECHNIQUES (TRIG, LOG, EXP FUNCTIONS) Mathematics Revisio Guides More Trigoometric ad Log Itegrals Page of 7 MK HOME TUITION Mathematics Revisio Guides Level: AS / A Level AQA : C Edexcel: C OCR: C OCR MEI: C FURTHER INTEGRATION TECHNIQUES

More information

CS 111: Program Design I Lecture 16: Module Review, Encodings, Lists

CS 111: Program Design I Lecture 16: Module Review, Encodings, Lists CS 111: Program Desig I Lecture 16: Module Review, Ecodigs, Lists Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago October 18, 2016 Last time Dot otatio ad methods Padas: user maual poit

More information

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015. Presetatio for use with the textbook Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 2015 Hash Tables xkcd. http://xkcd.com/221/. Radom Number. Used with permissio uder Creative

More information

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis Outlie ad Readig Aalysis of Algorithms Iput Algorithm Output Ruig time ( 3.) Pseudo-code ( 3.2) Coutig primitive operatios ( 3.3-3.) Asymptotic otatio ( 3.6) Asymptotic aalysis ( 3.7) Case study Aalysis

More information

Pattern Recognition Systems Lab 1 Least Mean Squares

Pattern Recognition Systems Lab 1 Least Mean Squares Patter Recogitio Systems Lab 1 Least Mea Squares 1. Objectives This laboratory work itroduces the OpeCV-based framework used throughout the course. I this assigmet a lie is fitted to a set of poits usig

More information

Improving Template Based Spike Detection

Improving Template Based Spike Detection Improvig Template Based Spike Detectio Kirk Smith, Member - IEEE Portlad State Uiversity petra@ee.pdx.edu Abstract Template matchig algorithms like SSE, Covolutio ad Maximum Likelihood are well kow for

More information

Parabolic Path to a Best Best-Fit Line:

Parabolic Path to a Best Best-Fit Line: Studet Activity : Fidig the Least Squares Regressio Lie By Explorig the Relatioship betwee Slope ad Residuals Objective: How does oe determie a best best-fit lie for a set of data? Eyeballig it may be

More information

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0 Polyomial Fuctios ad Models 1 Learig Objectives 1. Idetify polyomial fuctios ad their degree 2. Graph polyomial fuctios usig trasformatios 3. Idetify the real zeros of a polyomial fuctio ad their multiplicity

More information

Investigation Monitoring Inventory

Investigation Monitoring Inventory Ivestigatio Moitorig Ivetory Name Period Date Art Smith has bee providig the prits of a egravig to FieArt Gallery. He plas to make just 2000 more prits. FieArt has already received 70 of Art s prits. The

More information

Structuring Redundancy for Fault Tolerance. CSE 598D: Fault Tolerant Software

Structuring Redundancy for Fault Tolerance. CSE 598D: Fault Tolerant Software Structurig Redudacy for Fault Tolerace CSE 598D: Fault Tolerat Software What do we wat to achieve? Versios Damage Assessmet Versio 1 Error Detectio Iputs Versio 2 Voter Outputs State Restoratio Cotiued

More information

Recursive Procedures. How can you model the relationship between consecutive terms of a sequence?

Recursive Procedures. How can you model the relationship between consecutive terms of a sequence? 6. Recursive Procedures I Sectio 6.1, you used fuctio otatio to write a explicit formula to determie the value of ay term i a Sometimes it is easier to calculate oe term i a sequece usig the previous terms.

More information

The number n of subintervals times the length h of subintervals gives length of interval (b-a).

The number n of subintervals times the length h of subintervals gives length of interval (b-a). Simulator with MadMath Kit: Riema Sums (Teacher s pages) I your kit: 1. GeoGebra file: Ready-to-use projector sized simulator: RiemaSumMM.ggb 2. RiemaSumMM.pdf (this file) ad RiemaSumMMEd.pdf (educator's

More information

OCR Statistics 1. Working with data. Section 3: Measures of spread

OCR Statistics 1. Working with data. Section 3: Measures of spread Notes ad Eamples OCR Statistics 1 Workig with data Sectio 3: Measures of spread Just as there are several differet measures of cetral tedec (averages), there are a variet of statistical measures of spread.

More information

CSE 111 Bio: Program Design I Class 11: loops

CSE 111 Bio: Program Design I Class 11: loops SE 111 Bio: Program Desig I lass 11: loops Radall Muroe, xkcd.com/1411/ Robert H. Sloa (S) & Rachel Poretsky (Bio) Uiversity of Illiois, hicago October 2, 2016 Pytho ets Loopy! he Pytho, Busch ardes Florida

More information

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output File class i Java File Iput ad Output TOPICS File Iput Exceptio Hadlig File Output Programmers refer to iput/output as "I/O". The File class represets files as objects. The class is defied i the java.io

More information

CMSC Computer Architecture Lecture 12: Virtual Memory. Prof. Yanjing Li University of Chicago

CMSC Computer Architecture Lecture 12: Virtual Memory. Prof. Yanjing Li University of Chicago CMSC 22200 Computer Architecture Lecture 12: Virtual Memory Prof. Yajig Li Uiversity of Chicago A System with Physical Memory Oly Examples: most Cray machies early PCs Memory early all embedded systems

More information

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup Chapter 18 Vectors ad Arrays Bjare Stroustrup Vector revisited How are they implemeted? Poiters ad free store Destructors Iitializatio Copy ad move Arrays Array ad poiter problems Chagig size Templates

More information

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Pseudocode ( 1.1) High-level descriptio of a algorithm More structured

More information

BAAN IVc/BaanERP. Conversion Guide Oracle7 to Oracle8

BAAN IVc/BaanERP. Conversion Guide Oracle7 to Oracle8 BAAN IVc/BaaERP A publicatio of: Baa Developmet B.V. P.O.Box 143 3770 AC Bareveld The Netherlads Prited i the Netherlads Baa Developmet B.V. 1999. All rights reserved. The iformatio i this documet is subject

More information

Alpha Individual Solutions MAΘ National Convention 2013

Alpha Individual Solutions MAΘ National Convention 2013 Alpha Idividual Solutios MAΘ Natioal Covetio 0 Aswers:. D. A. C 4. D 5. C 6. B 7. A 8. C 9. D 0. B. B. A. D 4. C 5. A 6. C 7. B 8. A 9. A 0. C. E. B. D 4. C 5. A 6. D 7. B 8. C 9. D 0. B TB. 570 TB. 5

More information

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames Uit 4, Part 3 Recursio Computer Sciece S-111 Harvard Uiversity David G. Sulliva, Ph.D. Review: Method Frames Whe you make a method call, the Java rutime sets aside a block of memory kow as the frame of

More information

Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 3 More Flow of Cotrol Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 3.1 Usig Boolea Expressios 3.2 Multiway Braches 3.3 More about C++ Loop Statemets 3.4 Desigig Loops Copyright

More information

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments Ruig Time Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Most algorithms trasform iput objects ito output objects. The

More information

n n B. How many subsets of C are there of cardinality n. We are selecting elements for such a

n n B. How many subsets of C are there of cardinality n. We are selecting elements for such a 4. [10] Usig a combiatorial argumet, prove that for 1: = 0 = Let A ad B be disjoit sets of cardiality each ad C = A B. How may subsets of C are there of cardiality. We are selectig elemets for such a subset

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe CHAPTER 19 Query Optimizatio Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe Itroductio Query optimizatio Coducted by a query optimizer i a DBMS Goal:

More information

A New Morphological 3D Shape Decomposition: Grayscale Interframe Interpolation Method

A New Morphological 3D Shape Decomposition: Grayscale Interframe Interpolation Method A ew Morphological 3D Shape Decompositio: Grayscale Iterframe Iterpolatio Method D.. Vizireau Politehica Uiversity Bucharest, Romaia ae@comm.pub.ro R. M. Udrea Politehica Uiversity Bucharest, Romaia mihea@comm.pub.ro

More information

Module 8-7: Pascal s Triangle and the Binomial Theorem

Module 8-7: Pascal s Triangle and the Binomial Theorem Module 8-7: Pascal s Triagle ad the Biomial Theorem Gregory V. Bard April 5, 017 A Note about Notatio Just to recall, all of the followig mea the same thig: ( 7 7C 4 C4 7 7C4 5 4 ad they are (all proouced

More information

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8) CIS 11 Data Structures ad Algorithms with Java Fall 017 Big-Oh Notatio Tuesday, September 5 (Make-up Friday, September 8) Learig Goals Review Big-Oh ad lear big/small omega/theta otatios Practice solvig

More information

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments Ruig Time ( 3.1) Aalysis of Algorithms Iput Algorithm Output A algorithm is a step- by- step procedure for solvig a problem i a fiite amout of time. Most algorithms trasform iput objects ito output objects.

More information

Analysis of Algorithms

Analysis of Algorithms Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Ruig Time Most algorithms trasform iput objects ito output objects. The

More information

EE 459/500 HDL Based Digital Design with Programmable Logic. Lecture 13 Control and Sequencing: Hardwired and Microprogrammed Control

EE 459/500 HDL Based Digital Design with Programmable Logic. Lecture 13 Control and Sequencing: Hardwired and Microprogrammed Control EE 459/500 HDL Based Digital Desig with Programmable Logic Lecture 13 Cotrol ad Sequecig: Hardwired ad Microprogrammed Cotrol Refereces: Chapter s 4,5 from textbook Chapter 7 of M.M. Mao ad C.R. Kime,

More information

ECE4050 Data Structures and Algorithms. Lecture 6: Searching

ECE4050 Data Structures and Algorithms. Lecture 6: Searching ECE4050 Data Structures ad Algorithms Lecture 6: Searchig 1 Search Give: Distict keys k 1, k 2,, k ad collectio L of records of the form (k 1, I 1 ), (k 2, I 2 ),, (k, I ) where I j is the iformatio associated

More information

6.854J / J Advanced Algorithms Fall 2008

6.854J / J Advanced Algorithms Fall 2008 MIT OpeCourseWare http://ocw.mit.edu 6.854J / 18.415J Advaced Algorithms Fall 2008 For iformatio about citig these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 18.415/6.854 Advaced Algorithms

More information

the beginning of the program in order for it to work correctly. Similarly, a Confirm

the beginning of the program in order for it to work correctly. Similarly, a Confirm I our sytax, a Assume statemet will be used to record what must be true at the begiig of the program i order for it to work correctly. Similarly, a Cofirm statemet is used to record what should be true

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programmig Laguages Fuctioal Programmig Prof. Robert va Egele Overview What is fuctioal programmig? Historical origis of fuctioal programmig Fuctioal programmig today Cocepts of fuctioal programmig

More information

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs What are we goig to lear? CSC316-003 Data Structures Aalysis of Algorithms Computer Sciece North Carolia State Uiversity Need to say that some algorithms are better tha others Criteria for evaluatio Structure

More information

Getting Started. Getting Started - 1

Getting Started. Getting Started - 1 Gettig Started Gettig Started - 1 Issue 1 Overview of Gettig Started Overview of Gettig Started This sectio explais the basic operatios of the AUDIX system. It describes how to: Log i ad log out of the

More information

Descriptive Statistics Summary Lists

Descriptive Statistics Summary Lists Chapter 209 Descriptive Statistics Summary Lists Itroductio This procedure is used to summarize cotiuous data. Large volumes of such data may be easily summarized i statistical lists of meas, couts, stadard

More information

Counting Regions in the Plane and More 1

Counting Regions in the Plane and More 1 Coutig Regios i the Plae ad More 1 by Zvezdelia Stakova Berkeley Math Circle Itermediate I Group September 016 1. Overarchig Problem Problem 1 Regios i a Circle. The vertices of a polygos are arraged o

More information

condition w i B i S maximum u i

condition w i B i S maximum u i ecture 10 Dyamic Programmig 10.1 Kapsack Problem November 1, 2004 ecturer: Kamal Jai Notes: Tobias Holgers We are give a set of items U = {a 1, a 2,..., a }. Each item has a weight w i Z + ad a utility

More information

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1 CS200: Hash Tables Prichard Ch. 13.2 CS200 - Hash Tables 1 Table Implemetatios: average cases Search Add Remove Sorted array-based Usorted array-based Balaced Search Trees O(log ) O() O() O() O(1) O()

More information

CS 111: Program Design I Lecture # 7: Web Crawler, Functions; Open Access

CS 111: Program Design I Lecture # 7: Web Crawler, Functions; Open Access CS 111: Program Desig I Lecture # 7: Web Crawler, Fuctios; Ope Access Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago September 13, 2016 Lab Hit/Remider word = "hi" word.upper() à "HI" Questio

More information

UNIVERSITY OF MORATUWA

UNIVERSITY OF MORATUWA UNIVERSITY OF MORATUWA FACULTY OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING B.Sc. Egieerig 2014 Itake Semester 2 Examiatio CS2052 COMPUTER ARCHITECTURE Time allowed: 2 Hours Jauary 2016

More information

Protected points in ordered trees

Protected points in ordered trees Applied Mathematics Letters 008 56 50 www.elsevier.com/locate/aml Protected poits i ordered trees Gi-Sag Cheo a, Louis W. Shapiro b, a Departmet of Mathematics, Sugkyukwa Uiversity, Suwo 440-746, Republic

More information