New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Foundations of Computer Science

by: Reed Aufderhar

Foundations of Computer Science CS 1030

Marketplace > Utah State University > ComputerScienence > CS 1030 > Foundations of Computer Science
Reed Aufderhar
Utah State University
GPA 3.85

Linda Duhadway

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Linda Duhadway
Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 40 page Class Notes was uploaded by Reed Aufderhar on Wednesday October 28, 2015. The Class Notes belongs to CS 1030 at Utah State University taught by Linda Duhadway in Fall. Since its upload, it has received 11 views. For similar materials see /class/230439/cs-1030-utah-state-university in ComputerScienence at Utah State University.

Similar to CS 1030 at Utah State University

Popular in ComputerScienence


Reviews for Foundations of Computer Science


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/28/15
342009 Chapter 8 con39t Algorithms and Programming Languages I Algorithms and Programming programming is all about designing and coding algorithms for solving problems the intended executor is the computeror a program executing on that computer instructions are written in programming languages which are more constrained and exact than human languages Algorithms and Programming the level of precision necessary to write programs can be frustrating to beginners but it is much easier than it was 50 years ago early computers ENIAC needed to be wired to perform computations with the advent of the von Neumann architecture computers could be programmed instead of rewired an algorithm could be coded as instructions loaded into the memory of the computer and execute l Machine Languages the rst programming languages were known as machine languages a machine language oonsists of instructions that correspond directly to the hardware operations of a particular machine ie instructions deal directly with the computer s physical components including main memory registers and memory cells in the CPU very low level of abstraction machine language instructions are written in binary programming in machine language is tedious and error prone code is nearly impossible to understand and debug Machine Languages excerpt from a machine language program oouoooouoooooo11o1oooo11oo1o1o11o11ooo11o11ooo11o1111oo1o111oo11ooo11o111ooooo 111uoooooooouooo11oo111o11ooo11u11ooo11oo11oo1oo1o11111o11ouo11o11o1111o11o11o o 1 u o 1 11711 1 a E E e 6 m 5 5 m o oo11oo1o1o11o111oo11po1ooo11o11ooo1o11111o1o11111o1ooo11oo1o1oo1ooo11o11 1o11o1111o111ou11o111o1ooo111oo1ou11oo1o1o11oooo1o11o11o1uoooooooo11o1m1o11uo i oo1o11o1ou1o11o111oooooooooo110oo11o11o1111u111u1o1o111o1oooooooooooouoooooooo l HighLevel Languages in the early 1950 s assemblyanguagesevolved from machine languages an assembly language substitutes words for binary codes much easier to remember and use words but still a low level of abstraction instructions corrspond to hardware operations in the late 195039s hghlevelanguageswere introduced highlevel languages allow the programmer to write code closer to the way humans think as opposed to mimicking hardware operations a much more natural way to solve problems plus programs are machine independent 342009 HighLevel Languages Program Translation tW high leVel languages that Perform the same taSk using a highlevel language the programmer is able to in JavaScript and C reason at a highlevel of abstraction but programs must still be translated into machine lthtmigt 611M Dave Reed language that the computer hardware can if hellohtmi Dave Reed 77gt Tms pmgram displays a gl eetmg d This page displays a greeting 77gt N understandexecute IT 777777777777777 77gt include ltiostreamgt he include ltstringgt ad lt 39legt6reetingslttitlegt usmg namespace 5m head int mam there are two standard approaches to program body sm39p type extjavascriptquot sm ng userName tranSIatlon usem e prompt quotEnter your namequot quotquot out quotEnter your namequot ltlt endl t t t documentwritequotHe llo quot username uquot aquot 59mm 39 In erpre a ton E wpt can ltlt IHe llo ltlt userName ltlt I compilation 4mm tum 0 Program Translation Interpreters realworld analogy translating a speech from one language to for program translation the interpretation approach relies an ther on a program known as an interpreterto translate and an interpreter can be used provide a realtime translation execute highleve Statements the Interpreter hears a phrase translates and Immediater speaks the translation the Interpreter reads one highlevel statement at a time ADVANTAGE the translation is immediate immediately translating and executing the statement DISADVANTAGE if you want to hear the speech again must before processing the HGXt one interpret a over a ain JavaScript is an interpreted language a translator or compiler translates the entire speech offline the translator takes a copy of the speech returns when the entire speech is translated ADVANTAGE once translated it can be read over and over very quickly DISADVANTAGE must wait for the entire speech to be translated Interpreters Compilers the compilation approach relies on a program known as a compYer to translate the entire highlevel language program into its equivalent machinelanguage instructions the resulting machinelanguage program can be executed directly on the computer 1 W 2 Min 3 7 mm f l Eb gun yew 5mm meme werl ld tle i if 7 nun V V l l nu ltpt l V quot V r Hi 1 av 39 mmji A dmw AVweluhlml v was lthe ygt Sm q 2 tgxzjavnsnlptquot usernanle a prnmnttquotEntsr your namequot W ducmentwrnaquotltpgtugllu quot t usamame A quotrapm lt Crlptgt jbady lthml um l Hello Davel most languages used for the development of commercial J software employ the compilation technique C C I 5mm JavaSnnm Mgmm4 mmldcdm a L The mltrprclnm m way hows r mmmi mus mm mman mum m mm Willun m brmkr 11m m mm mun nl m 3MP dupL m in ch wa mt 342009 Compilers quotinclude mineanb mduae string using nameSDa a 5m m mama r 397 String userName w cw WW um nmm mm quotEnter ynur namequot my mumquot n userName H mm ltlt Helln quot userName mm a 1 2 A main um me may mum x n and Dmdmsnmdnnc lungwgcvusizm a mg l a axe 1nd mm m may mutx m mam Mus mman mm r am Interpreters and Compilers tradeoffs between interpretation and compilation interpreter producs results almost immediately particularly useful for dynamic interactive famrs of web pags program executes more slowly because mch statement has to be translated before it can be executed Interpreters and Compilers compiler underlying hardware program runs very fast after compilation must compile the entire program before execution used in large software applications when speed is of the utmost importance producs machinelanguage program that can run directly on the cs 1030 Foundations of Computer Science What is a Computer Computers are incredibly fast accurate and stupid humans are incredibly slow inaccurate and brilliant together they are powerful beyond imagination Albert Einstein What is a Computer 9 Desktop Supercomputer PDA personal digital assistant g Embedded computers A Computer A device that receives stores and processes information 511 3320111 quotrut3r D esktop Computer Laptop C amputer Palmtop Crey 39 3 DXI JPTM Dell Dimensionm iii 0 Apple iB a 0L PalmTM 111131 Hardware Hardware the stuff you can touch The easiest way to tell the difference between hardware and software is to kick it If it hurts your toe it s hardwarequot Anonymous Hardware Hardware CEDROM drive secondary memory System unit contains CPU RAM main memory and other supporting components Harddisk drive secondary memory it Screen output device Floppy drive secondary memory Input device5 i Speakers output device Kejbo aid in put device 393 Mouse 4 input device CPU Central Processing Unit f CPU made of circuitry electronic components wired together to control the CPU is the quotbrainsquot of the computer the ow of electrical signals the circuitry is embedded in a small silicon chip 12 inches square responSibie for contrOiiing inner despite its small size the CPU is the most complex part of a computer CPU circuitry can have 10039s of millions of individual components worki ngs CPU fetches data CPU receives data and instructions and instructions from from memory keybo and mouse Central InputOutput BUS Processing Unit 3115 Devices CPL 10 CPU performs CPU performs computations stores computations sends results and results to screen instructions in memory speakers punter 10 CPU the CPU works by repeatedly fetching a program instruction from memory and 00101101 11131 01010111 01100101 01101 01100011 EXECUting that inStrUCtion 01101111 01101101 01100101 011 01101111 01000011 individual instructions are very simple 01010311 00100101 eg add two numbers or copy this data 00030001 complex behavior results from incredible mo speed 11131031 01013111 01031111 01031111 01011031 01013101 13101131 Memory Memory If you have N bits You can represent 2N values I Isl lbit a2values 0 1 Zbits H4values 00 01 10 11 a Evalues 000 001 010 011 100 101 110 111 0 1 a 16 values 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1111 EEEEEEEE 39 w 039quot D i 1 I 0 I 0 0 EEEEEEEE 398 0 1 I 0 I 0 0 I a 2 values 00000 00001 00010 00011 00100 00101 00110 00111 01000 01001 0101 s a 39 000000 000001 000010 000011 000100 000101 000110 000111 001000 a 128 value 0000000 0000001 0000010 0000011 0000100 0000101 0000110 0000111 a 256 value 00000000 00000001 00000010 00000011 00000100 00000101 00000110 9bits a 512 values 000000000 000000001 000000010 000000011 000000100 000000101 10bitsgt 1024 values 0000000000 0000000001 0000000010 0000000011 0000000100 0000000101 mdmmbw zzzazz m a S E 3 N bits a ZNVEilues Memory Memory memory capacity is usually specified in bytes 3 bits 1 Byte Bytes 1 Kilobyte KB Bytes 1 Megabyte MB A Bytes 1 Gigabyte GB z Bytes 1 Terabyte TB 58921 12 2975482 w e I c m e I 0 modern computers useacombination s i 0 i i 0 of memory types each With ItS own 1 2 performance and cost characteristics 3 4 5 6 7 8 9 10 I G o o D B Y E I RAM chips Haul disk Fiuppy 45L mupnct disk to Main Memory Main Memory Cache RAM random access memory Volatile Fast Expensive g Secondary Storage Nonvolatile Slower Less Expensive Many different varieties Input Output Devices g Blackboard Notice some of these are not actually IO devices Everyone that is registered already has an account A number Banner password 0 l SYIIabUS httpwwwcsusuedulindadcle30calendarhtm e Calendar httpwwwcsusuedulindadcle30syllabushtm l39 F Englander The Architecture of Computer Hardware and Systems Software 2nd edition Chapter l Figure 01 06 Inputoutput devices 5 Let s Add Style We use css Style rules are made up of propertyvalue pairs color red textalign center These can be added to individual elements or groups of elements 1272009 CSS Adding style inline embedded external style sheet a combination of the above We will be using an external style sheet external style sheet put all your style rules in a separate style sheet and then connect the external style sheet to the document by using a linktag or the import statement in the css le color red This is a plain text le with css extension g Adding Style in the htm le linktag ltink hrefquotstylecssquot relquotstylesheetquot typequottextcssquot gt This connects the css le with the htm le Put the link tag in the head section CSS There are many propertyvalue combinations Most are listed in the Adding Style document You can nd a link to this document on the handouts page in Blackboard color property The color property sets the color of the text A speci c color can be represented in a variety of ways color FF2288 color rgb255 34 136 These both represent the same color 5 textalign property this property allows you to change the default alignment of the text Possible values left nght center justify Egtltam le textalignoener 1272009 5 backgroundcolor Sets the color of the background Use the color values Egtltample backgroundcolor DDEEZZ backgroundcolor rgb255 238 34 g backgroundimage Allows you to put an image in the background Use a url for the value Egtltample backgroundimage urltexturejpg border You can put a border around any element There are three border properties that you borderwidth borderstyle bordercolor g backgroundrepeat When you have a background image you can decide if it displays the image onetime backgroundrepeat norepeat a row of imags across the page backgroundrepeat repeatx a column of imags down the page backgroundrepeat repeaty the image tiled over the entire element backgroundrepeat repeat borderwidth Specify the width of the border using a length A length consists of a number followed by a 2letter unit abbreviation Egtltample borderwidth 2px borderwidth 3in borderwidth 2cm 1272009 borderstyle borderstyle 39You can spedfy the type of border to use none is the default value which means the 39The ChOices are element has no border none ridge If you don t change the border style nothing will dotted inset display even if you have set border color andor dashed outset border39C r solid Remember you must change border style if you double Want the element to have a border groove bordercolor Box Properties Use the regular color values for this propery Example bordercolor 802086 bordercolor rgb128 160 134 image copied from httpwww hfml 39 39 nif Additionalstyle properties Example For additional style properties see the Adding Create an external style sheet StYIe Document Add the style sheet to our example web page httpwwwcsusued ulindadcle30 handoutsaddingStylehtm 2242009 Output via Text Boxes I a button provides a simple mechanism for user Chapter 7 continued interaction in a Web page I by clicking the button the user initiates some action EventDriven Pages I a text boxis an eventhandler that can display text a word or phrase I unlike an aleit window the text box appears as a box embedded in the page I text can be written to the box by JavaScript code ie the box displays output Output Via Text Boxes Output Via Text Boxes for example we COU39d re39 general form of a text box element I implement the lucky a at i i e number page using a text ltinput typequottextquot idquotBOXNAMEquot Lucky Davevs Gm To you bOX size quotNUMCHARS quot value quot INITIALTEXT quot gt r 39 e 39 Vf gmbmmmg 739 rumlumsu 39 the teXt box conta39mng I the TYPE attribute of the INPUT element identifies the element C 39 k N quot the random number is to bea text box 7 embedded In the page I the ID attribute gives the element an Identifier so that it can be yeeeeeeemeeeef doesnuc re uire the user referenced sometimes referred to as the name of the element I I hq I d I the SIZE attribute specifies the size of the box number of WWW WWI V to C ose t e a ert Wm 0W characters that fit after eaCh number I the VALUE attribute specifies text that initially appears in the box I htiiii 2 it 2eg mldispieys lt1 mm number at the Click of IWhen the bUtton iS 2 quotT quot clicked the JavaScript 6 4mquot V commands are tttle Dave39s Lucky Number quottttlee Output Via Text Boxes 3 exeeueee 1P5Styiibvteitsal1QlECE tamplquotv I I I I hEeLucky Dave39s Gift To Youilil the commands t0 dISplay teXt In a teXt bOX a JavaScrIpt aSSIQHment 1 elei le ee eee equotleeleliieiieii l i 23112Ze tiyiiik LeDe i genegate adrandom I I I I it our QUEFEHIEE U39 71le El Ol IE 5 D I is used to asSIgn to its value attribute it Mme e w M 311 22X a55igni o I I 15L um mk39 u tuni r 39Hl u as part of the assignment must speCIfy the absolute 2 Ah I h 2239 VD39 39 r ut vwe39tevtquot 1c quotmm erBrxquot new v3 ue Ias a resu t eac name Of the box mquot Mb 1quot quotquot quot Wm quot39 EX 39 button click yields a the general form is 3 gm e quot 39 new umber 39 the b X documentgetEIementByld39BOXNAME39value VALUETOBEDISPLAYED Input via Text Boxes text boxes can also be used for receiving user input the user can enter text directly into the box that text can then be accessed by JavaScript code via the absolute name of the box document geElementById 39BOXNAME 39 value note that the value retrieved from a text box is always a string if the user enters a number say 93 then the absolute name will access quot93quot similar to prompt you must use parseFloat to convert the string to its numeric value 2242009 I Input via Text Boxes example we can create a temperature conversion page the user enters the Fahrenheit temperature in a text box at the click of a button the input is accessed and conveited to Celsius another text box is used to display the conveited temperature L htltll l lt rv ronvernhrml lnve Reel v z 397 Thu Age Converts temperatures from Fahrenheit m elsius 77 4 e lfahrBox IS 3 64 used for input 7 ti ieTemperature Conversion Page tlrle 3 head 9 my abody I JudTemperature Conversion Pager he I err uthe button 5 13 e 14 Enter a temperature in degrees Fahrenheit 39 1 elllput type text id talianx 519 tit value 16 UP r n 1 rtnput type buttonquot value39iionvert to Celsius 19 ontlitt tempInF tlocumentgetE enBvItM tahrBox39value 39 39 zo templnF rse oatrtemplnpi 21 tem InC J9 39 tempInF e 3277 2L documentgerElementhIdt39Celstussox39value tempInCquot gt 23 up 2L 1quot 25 Equivalent temperature 39in degrees els39ius Eb ltillput type text id ize s1uBox39 siequot11i value gt n e t temperature 25 boutquot 29 htm39l Temperature Conversion Page Ice 1 s lu SBOX IS used for Enter a temperature m degeei Fahrenheit E12 0 Immanu Equn olent temperature m degees Celsn 39 mu gamma may v Input and Output note the same text box can be used for both input and output can modify the conversion page to allow for entering a temperature in either box then convert to the other Temperature Conversion Page Windows Internet Explorer i r ElChapter convertLhtml 4 Temperature COI39WEl39SlOl39l Page lquotquot l r gt Home 39 Temperature Conversion Page Enter a temperature in a box and click on the desired box to convert Famenlmitbz FahraCelsius FahrltCelsius H3 3 Local intranet Input and Output can write a simple page in which the user can enter a number then double it by clicking a button Eil hapterF39tExerCise V 7 X gtgt 4 igl ouble the Number 77 H 39me 39 I Doubmthenumber J 391 Local intranet quot399 100 v a text area is similar to a text box but it can contain any number of text lines Text Areas general form of a text area element lttextarea idquotTEXTAREANAMEquot rowsNUMROWS colsNUMCOLS wrapquotvirtualquotgt INITIALTEXT lttextareagt the ID attribute gives the element a name so that it can be referenced the ROWS attribute specifies the height number of text lines of the area the COLS attribute specifies the width number of characters of the area the WRAP attribute ensures that the text will wrap from one line to the next instead of running off the edge of the text area 2242009 Text Areas unlike a text box opening and closing tags are used to define a text area I any text appearing between the tags will be the initial text in the text area I otherwise the contents of a text area are accessedassigned in the same way InputOutput via Text Areas hunk U r qrwrlwaitml lava Rwy lt W rim page Amain a personalized urwrimi in A ten area W Ll with Long Greeting rIrTI I 10 vliorly 1 14 Enter your last name uniut typo tglttquot I lJSTI JJlIIQBW sizes 15 ip p 17 Input vaequotlmrwn39 in 18 tvntliril f7 FU NALQ lag 20 message iieila 39 1 39 or may I 22 quot YDU iiltlllllix39t 39c o39 k Avenue 14 zlm iiiiigntgetEIuirisnfoIdI Was V 5 ip 1p 27 Lextarea H lHESsi eAf Ei row5quotJquot Cali41 gtlt tamp t3fr3 10 12 Enter your first name ltllmtlf r ylle fext nlz HrirNanwEm39 5129 15 w hr quotrNAiiieBox39JAalue on39im ue the user enters first and last names into text boxes a long greeting is constructed using the names and assigned to the text area lJOdy 30 hm Eureryour xsrnamelAlan 1am your m um lrmmg Clickfal Greellng 3 Lnial intranet mm v Dynamic Images just as you can use userinitiated events to change the contents of text areas and text boxes you can also dynamically modify images ltimg idquotfaceImgquot srcquothappygifquot altquotHappy Facequot gt causes the image stored in the file happy gif to appear in the page Notice the id attribute Dynamic Images you can change the image by reassigning its SRC attribute similar to the way that text boxesareas have their VALUE attribute reassigned documentgetElementById39faceImg39src quotsadgifquot replaces happy gif with sadgif Dynamic Image Example uuUaHythe 1 4mm Image IS set to z id pichirml Dave Reed 77 3 i7 This page allows the user to select from among two images vi 39 glf 4 1 5 6 head 7 t ltle Picture Fun t1 tie When a 8 Wield gt 9 button IS 10 riaolygt 11 11v styiea textialignzwnter gt Cllcked 12 IntHow do you feel today Ill 13 41mg idquotf1celmqquot srn iariwqif ait face image r Images IS 14 br hr r 15 input rype39lutton vallle 1 feel happy aSSgned a 16 ontlirk documentgetElenlentByIm39facelmg srt 39hsppygff39 gt 17 ampnluspampnhsp new le 18 lt1nput type39butt0n value I Feel MW 19 on ick documentgetEiementByILl faceImg39 1 sr39c satlgff 39 quot 20 mix 21 lt body 22 lt html 7 l l How do you feel today lmmnnma Dane 34 mi mm x mm v 432009 5 Chapter 16 Inside the Computer Transistors and Integrated CircuiB EIectrrcrty and Switches mode n computers are powered by electricity using electrical signals to store and manipulate information the components of a computer require electrical power to carry out their assigned task electricity generates the light that shines through a co uter screen illuminating the individual pixels that make up images and letters electricity runs the motor that spins the harddrive disk allowing information to be accessed main memory and CPU employ electrical signals to store and manipulate data bit patterns are represented by the presence or absence of electricity is a ow of electrons the negatively charged particles in atoms through a medium good conductors of electricity allow for the flow of electrons with little resistance eg copper silver gold other elements especially nonmetals are poor conductors e g carbon oxygen electricity can be quanti ed in amperesor Voltage amperes gauge electron few 1 amp is e ual to 624 quintillion 1013 electrons flowing past a given point each second Voltage measures the physical force produced by the ow of electrons standard household in United States has 110 to 120 volt outlets g Electr tyBasics l Elcrmcm is guarath m apmvct plant l39vrexample m cm or oil it lmmcxl m pludut s mm m g LPN ihiThestcmn ttunsnulr inL39 P w it The blades of un mum pm through am a e lincsm sscswhc mm mm and mm mm producing cleclneny nciywurmm pmvldzs pmtex at lights and appliances l Sw tches the most basic tool for controlling the ow ofelectricity is a sWZ39clr a switch can be flipped to connect or disconnect two wires thus regulating the ow of electricity between them Switches trait 31 current Hmeh Iim lwns mm power trim SI Transistors as we saw in Chapter 6 advances in switching technology have defined the generations of computers 1930 s electromagnetic relays served as physical switches whose onoff positions were con ro led by the voltage to a magnet 1940 s vacuum tubs replaced relays which were faster since no moving parts but tended to overheat and burn out frequen 1948 the transistor was developed by Bardeen Brattain and Shockley a transistor is a solid pieoe of metal attached to a wire that serves as a switch by alternatively conducting or resisting electricity transistors allowed for the development of smaller faster machines at a lower cost Transistors semiconductors are metals that can be manipulated to be either good or bad conductors of electricity l the first transistors were made of germanium and gold but modern transistors are constructed from silicon I through a process known as doping impurities are added to a slab of silicon causing the metal to act as an electrical switch r Transistors as Switches a PMOS transstoris positively doped so that the switch IS quotclosedquot when there is no current on the control wire but quotopensquot when current is applied Control 0 V Control 39 39 wire C LOS ED SW39ITC H OPEN SW TC H Transistors as Switches an NMOS transistoris negatively doped so that the switch Is quotopenquot when there is no current but quotclosesquot when there is current Comm II 39t39 are OPEN SWITCH Comm 5 39 wire CLOSED SWITCH From Transistors to Gates transistors can be combined to form a circuit which controls the flow of electricity in order to produce a particular behavior the term gate suggests a simple circuit that controls the flow of electricity in the case ofa NOT gate the ow of electricity is manipulated so that the output signal is always opposite of the input signal example consider the following circuit combining two transistors this circuit known as a IVOTgalE Gates and Binary Logic we can think ofa gate as computing a function of binary values szorsuppl l539 0 represents no current 1 reprsenis current 0 1 Power supply 15w NOT gale lnpm 5quot 0mm inpm ulpui lnpul gt0 Oulpul l 0 the symbol in the left triangle w circle is often used to denote Gmou qund a NOT ga NOTgnic will UV mpm NOTgmc wiihSV39 mpm the Tl r tabem the right describes the mapping of input to output The And Gate The Or Gate Pmmi supph if x cm mm mm mm ANDgal lnpml mun lnnutz AND outuut o J u o 1 1 J o n 1 o 1 J 1 l 1 1 1 muml a OR gate Mm mpurs my and s v AND gate with inputs Gates and Binary Logic AND OR and NOT gates can be combined to construct all the circuitry required to store and manipulate information within a computer There are other gates that are commonly used such as NOR and NAND gates 3262009 Chapter 11 Conditional Execution Conditional Execution m far aii ofthe code you naye yritten nas been Wandvana y ExamEd tne boMei carried out stateneits in the sanre set cm contrast rnany programming tasks require code that ream a erently under yary irig irm instances ar conditions e a a smdmt s EEUVSE grade amends qu nsne ayaage e a an an test raeures ramming mm a sutiatt messed riert eg memeneata gamedwmds wan deidls a piayer rneyes h Conditional Execution onmmnaEXEILmn refers to a program s ability to execute a statement ar sequent true e of statements aniy it rne condition is g If Statements n Java tript tne sirnpiest form ofconditunal statement s the irstaterrrmt are a ani taienitsarne mrdnm is we tuta di amt anion is takm it the mdnon is ruth called the aeetase the ase Easels Dunmal g If Sta temenis genaaitarrn ofthe ifstatement if BooLEANJEsT sTATEMENTstEtuTEDJFJRuE ei s STATEMENTSEXEUTEDI FJALSE Braces n If Statements mme pmple prefer braces on separate iines formatted like tnis t aootEANJEsn STATEMENTSiEECUTEDJFJRUE eise sTATEMEngxEcuTEDJEFAtsE 3262009 I Braces In If Statements Boolean Tests th I t bl b t b t t39 the test that controls an if statement can be any boolean 39 e39 erstye 395 agcep a e u econs39sen 39 expresson ie an expression that evaluates to either properly aligning the code wrth Ifelse lining up and true or false statements indented is central in producing code that is b I f d I I easy to read and modify oo ean tests are orme usmg re atona operators because they test the relationships between values technically you can omit the braces if there is only one Relational Comparison De ned statement Operator by the Operator however THIS IS STRONGLY DISCOURAGED equal to NOTE can lead to tricky errors If the code IS ever modified m is for comparisons 4 less than or equal to is for assignments r greater than greater than 0139 equal to If Statement Examples 39r d lt em I 1 glrgr iit39Wou39 failed Time to hit the btloksquot i r the boolean test in an if statement 39I F rgrade DU determines the code that will be executed agggu fg ggg IF 0W W m d have i ft39ljf39f i39lwd if the test is true then the code inside the 1 39quotearne quot d1 fr quot more points i subsequent curly braces will execute i if the test is false then the code inside the curly r braces following the else will execute c giige ni grade n mauled note that if the test is false and there is no else a1erti n 1legdigi 9395333 33543135 h case the program moves on to the statement i159 ll Wm mmm directly after the alertfllmngratulations you passedquot gratin hm an if statement is known as a control statement since its purpose is to control the execution of other statements Example Within a Page 1 ht l m 2 ltlt2139filerrwgthtrrl Dave Reed vgt 3 d This program warns a student of a Failing grade 7gt 4 s if y 5 6 ltheadgt l 7 titlgt If Demo Page rt39ltlgt 3 Lets do a web page that calculates taxes 9 function Sh H to a failing grade I 12 13 The tax rate IS 18 when Income IS less than 14 15 grade documentgetElementByIdfquotgr acleonquotfivalue 16 grade parseFioattgradei I I I I 1 W 7 M The tax rate IS 32 when Income IS greater than 1 13 J quot391 Li ln c le l kquot t 4rtl Wu fai e l Time to t fl vuc lt i 21 7 22 rim1m 23 ahead 24 25 body 26 4p 27 Your grade ltinput type textquot idquotgradeBoxquot size5mquot valuequotquot 39 23 gt 29 p 30 input typequotbuttonquot value ciick For Messagequot onclick39Shov39llessagelzquot s 31 gt 32 c 39 bode 33 html gt 3262009 Accesslng Text Fields recall that values entered via text boxesareas are always returned as string if documentgetE19mentById39age39value gt 19 aleztquotYou are old enough to votequot else 1 alertquotsory You are too young to votequot will say that a 2year old can vote but a 102year old can39 I Example I Let39s try that Accesslng Text Fields I ifyou wish to treata value obtained from a text box or text area as a number you must use the parseFloat function to convert it age parsnl loatmocummgtE1nlIlantEyId39aga39 value 1 age gt 18 alartquotYou axe old enough to Votequot l e1se I alartquotsorzy You are too young to votewl will behave as expected gt Nested If Statements programming tasks often require code that responds to more than one condition thi can be accorrpl39shed by nesting one if statement 39nside of moths example39 demrmining windthill windschill is only de ned for temperatures less than or equal to 50 degrees the initial if test is m determine if it is a valid tenper ture to calculate windschill the nested if statement only execums W the cute test is true Nested If Statements lF temllerature n lF mmlsneerl 3 r ndclull e temperature else mndcmll e 25 74 s D Z tEmDErature else alertC39h l39rldachl39ll ls tletmed only lF temperature ltgt 5mquot mrnltmll Na 0427S39temllerature e 357SJ MathnnMwlndSDEedr 015 Chapter 3 The Internet and the Web 252009 History of Internet I recall the Internet is a vast international network of computers I the Internet traces its roots back to the early 19605 I MIT professor JCR Licklider published a series of articles describing a Galactic Network of communicating computers I in 1962 Licklider became head of computer research at the US Department of Defense s Advanced Research Project Agency 4 RPA I in 1967 Licklider hired Larry Roberts to design and History of Internet the ARPANet precursor to the Internet became a reality in 1969 I it connected computers at four universities UCLA UCSB SRI and Utah I it employed dedicated cables buried underground the data transfer rate was 56K bitssec roughly the same as dialup services today I the ARPANet demonstrated that researchers at different sites could communicate share data and run software remotely ARPANet Ithe ARPANet was intended to connect only military installations and universities participating in government projects by 1971 18 sites were connected most used Interface Message Processors IMPs which allowed up to 4 terminal connections at the site sites labeled with a T utilized Terminal Interface Processors TIPs which allowed up to 64 terminal connections at the site ARPANet Growth Iby 1980 close to 100 sites were connected to the ARPANet satellite connections provided links to select cities outside the continental US ARPANET GEOGRAPHIC MAP OCTOBER I080 F 339 g 1 1m VZI uncum A m f Owl 4 I l f I IMHH ImMLEQ K B r 2 I ms 39 XEROX my E mammal M X NP P quot I l 39Cnu Mum In E JMxvmm 7mm A A mm II SATELLITECIRCUIT gt IMP TIP PLURIBUS IMP PLURIBUS TIP ARPANet Growth in the early 19805 the ARPANet experienced an astounding growth spurt I applications such as email newsgroups and remote logins were attractive to all colleges and universities I by 1984 the ARPANet encompassed more than 1000 sites 252009 NSFNet to accommodate further growth the National Science quotInternetquot Foundation NSF became involved with the ARPANet in 1984 NSF funded the construction of highspeed transmission lines that W 39d f rm the backbm e the expanding quotem k the term Internet was coined in recognition of NMNIEI ll New iwi the similarities between the NSFNet and the interstate highway system backbone connections provided fast communications between principal destinations analogous to Intest39ate highways connected to the backbone were slower transmission lines that linked secondary destinations analogous to state ngnways local connections were required to reach individual computers analogous to city and negnbornooo39 roads Internet Socnety II II Internet Society is an international nonpro t organization Internet founded in 1992 it maintains and enforces standards ensuring that all computers on the Internet are able to communicate with each other I recognizing that continued growth would reqUIre it also organizes committees that propose and approve new significant funding and research the government Internetrelated technologles and software decided in the mid 905 to privatize the Internet control of the network s hardware was turned over to telecommunications companies and research organizations eg ATampT Verizon Qwest Sprint research and design are administered by the Intenet Society Internet Growth until recently the Internet more than doubled in size every 1 or 2 Iumpulors on Your Ills lnlemm l mmuman SWEJV39Umelra somre Cons omumy lalyi m Paul Baran the design of the ARPANet was influenced by the ideas of Paul Baran a researcher at the RAND Institute Baran proposed 2 key ideas dLstrbuted network packetswitchhg 252009 Distributed Networks recall the ARPANet was funded by the Dept of Defense for communications as such it needed to be resistant to attack or mechanical failure Distributed Networks Minimum martian1 Inr Iti FIE I minimum linerWyn em Dim mm NilMn Packet Switching in a packetswitching network messages to be sent over the network are first broken into small pieces known as packets these packets are sent independently to their final destination 539 Packet Switching l paclrcl l i 2 p4 packcl E NETWORK 1 1145 lmcrncrl pacle 3 packt l 2 i g Mariel 4 hackcl 3 W4 8 packcl 5 packcl 5 l The massage is broken into small packets each l bClDLl for lclivcry Z The packcls lravcl independently across the nelwork perhaps arriving al lhcir Llesllnalion oul of orrlcr 3 The packels arc reassembled in he correcl order to obtain lhr original message Advantages of Packets l sending information in smaller units increases the efficient use of connections large messages can39t monopolize the connection 1 Advantages of Packets routers specialpurpose computers that direct t e flow of messages can recognize failures or congestion and reroute the packet around trouble areas 252009 Advantages of Packets l breaking the message into packets can improve reliability since the packets are transmitted independently it is likely that at least part of the message will arrive even if some failures occur within the network software at the destination can recognize which packets are missing and request retransmission 1 Protocols and Addresses the Internet allows different types of computers from around the world to communicate this is possible because the computing community greed upon common protocols Protocol set of rules that describe how communication takes place the two central protocols that control Internet communication are I Transmission Control Protocol 70 I InternetProtocoIF Protocols and Addresses these protocols rely on each computer having a unique identifier known as an IPaddress analogy street address zip code provide unique address for your housedorm using this address anyone in the world can send you a letter an IP address is a number written as a dotted sequence such as 147134284 each computer is assigned an IP address by its Internet Service Provider ISP some ISPs eg AOL most colleges maintain a pool of IP addresses and assign them dynamically to computers each time thev connect TCPIP Transmission Control Protocol TCP controls the method by which messages are broken down into packets and then reassembled when they reach their final destination Internet Protocol IP concerned with labeling the packets for delivery and controlling the packets paths from sender to recipient g TCPIP er U lTCqullumson um xenpiom s 252009 I Routers and DNS the Internet relies on special purpose computers in the network routersare computers that receive packets access the routing information and pass the packets on toward their destination domain name serversare computers that store mappings between domain names and IP addresses domain namesare hierarchical names for computers eg bluejaycreightonedu they are much easier to remember and type than IP addrsses domain name servers translate the names into their mm mndinn TP addrp P Routers and DNS 3 m domain mm sener mars up w i ii in at mind i request is 2 m brower mum mt sxnm sum us paged on m annihu domainrname germ lln nw Heighten ellu mm the URL m mm n m m local damaimmm serve Q s Finaliin iequesl m ihc rule 1 xhtm t ech mm the inmn ulead is 47 mm Thcugcrzmen iimURL wwwm39em mmdu indexmmi mmeAddm ba mww buywyr Chapter 11 continued Conditional Execution 3262009 Cascading If else Statements nested ifelse structures are known as cascading ifese statements because control cascades down the branches the topmost level is evaluated first ifthe test succeeds then the corresponding statements are executed and control moves to the next statement following the cascading if ifthe test fails then control cascades down to the next if test in general control cascades down the statement from one test to another until one succeeds or the end of the statement is reached I Cascading If else Statements example nested ifelse structure if grdde 539 60 l execuch 1I39 alerLquotYou lailed Time Lo hit the booksquot I umda nll else if grade lt 90 L executed 1i 39 alertC You passed but could do better3 J gramcull executede Else l Hilde nu alertquotCongratulations You got an Aquot executed if gru n ii A Cleaner Notation when it is necessary to handle a large number of alternatives nested if else statements can become cumbersome and unwieldy multiple levels of indentation and curly braces cause the code to look cluttered make it harder to readunderstand A Cleaner Notation example nested if statements vs a more readable elseif if grade lt 60 if grade lt 60 l ettercrade quotFquot ettercrade quotFquot else else if grade lt 70 if grade lt 70 letterGrade quotDquot letterCrade quotDquot else if grade lt 80 else lettercrade quotCquot if grade lt 80 lettercrade quotCquot else if grade lt 90 lettercrade quot8quot else if grade lt 90 else letterCrade 39B39 lettercrade quotAquot lettercrade quotAquot Die Roll Example consider a Web page that simulates the roll of a single die will use an image to display the die will use a button to initiate the die roll when the user clicks the button a random die roll is selected and the corresponding image is displayed BEE l iii 5mm v Clicklo Flull 3262009 Die Roll Page Example the Randomlnt function 39 Let39s bund that page from random js is used to select the random ro depending on the roll value the correct image is displayed since more than two possibilities a cascading ifelse is needed Generalizing Code note that each case in the cascading ifelse follows the same pattern if roll 1 i Generalizing Code document getElementById39die39src quotdie1gifquot i else if roll 2 39 39 39 39 document39getElementByIdNie m quotdielgifquot this entire cascading if else structure could be replaced by the followmg else if roll 3 document getElementById39die39src quotdie3gifquot else if roll documentgetElementById39die39src quotdie4gifquot else if roll documentgetElementByld39die39 Srlt quotdieSgifquot document getElementById 39die39 src quotdiequot roll quotgifquot else documentgetElementById39die39src quotdie6gifquot Counters Counters in software applications if statements are often 39 any Variabiethat is used to record occurrences used to count occurrences of conditional or user 0f enevent IS known as a COU7ter initiated events Initially the counter is set to zero e 9 count the number of times dice rons come up each time the specified action occurs the counter is doubles incremented I I eg count the number of times the user guesses a 39 after 3 939Ven tlme PerlOd the value St0red In the num ber correcuy counter Wlii tell you the number of times the desired event took place documentgetElementByIdC numRollsquotveilue parseFloatldocumentgetElementByIdquotiiumRolls valiie l Example Let39s count lucky numbers 3262009 Logical Connectives sometimes simple comparisons between two values may not e adequate to express the conditions under which code should execute JavaScript provides operators forexpressing multipart tests IogicaAm w represenE me conjmction of two rhinos TESTl ampamp TESTZ is hue if borh TESTl and TESTZ are true if rolU A4 rol 2 4 l code to be executed when double fours are rolled Logical Connectives logical DR I I represenis me disjmction oftwo min s TESTl TESTZ is oue if either TESTl or TESTZ are true 1f lrolll 4 ll ro112 7 4 l Code to be executed when at least one four is rolled l logicaNOTU represenE negation TEST1 is hue only if TESTl is false if I r0111 4 ll Code 15 a four l to 4 l l to be executed when neither roll Chapter 8 Algorithms and Programming Languages 2282009 Algorithms the central concept underlying all computation is that of the algorithm Algorithm a stepbystep set of instructions to accomplish a task Algorithms programming can be viewed as the process of designing and implementing algorithms that a computer can carry out a programmer s job is to create an algorithm for accomplishing a given objective then translate the individual steps of the algorithm into a programming language that the computer can understand Algorithms example programming in JavaScript l we have written programs that instruct the browser to carry out a particular task I given the proper instructions the browser is able to understand and produce the desired results g Example programming in JavaScript we decided what functionality we wanted the web page to have we wrote the JavaScript code that would implement that functionality given the proper instructions the browser is able to understand and produce the desired results Algorithms in the Real World EASY COOK DIRECTIONS TOP OF the use of algorithms IS not E 39 39 39 BlL6cu sof water Slirin computing RINSE 39 egITECiPes for baking 39 mix well Makes ahoul 2 cups eg directions to your house POUR Macaroni into I or quul39l microwuvuhlc howl Add 1 cups hot water 0 MICROWAVE uncovered on HIGH 12 0 l4 minulcs or unlil walcr is absorbed stirring every 5 minutes Continue as directed above 2282009 g Algorithms in the Real World ll Algorithms there are many unfamiliar tasks in life that we Specifying the solution to a problem in could not complete without the aid of precise steps may be difficult 39nStrUCt39OnS However once the problem39s solution is in order for an algorithm to be effective it must be designed and written down in the form of an stated in a manner that its intended executor can algorithm that particular problem can be understand solved by anyone capable of following the a reCIpe written for a master chef Will look different than a recipe written for a 12 year old algorithm steps as you have already experienced computers are more demanding with regard to algorithm specifics than any human could be Designing amp Analyzing Algorithms Designing amp Analyzing Algorithms of people understanding the problem initial condition room full of people goal identify the oldest person assumptions a person will give their real biithday if two people are born on the same day they are the same age if there is more than one oldest person finding any one of them is okay 1 understand the problem 2 devise a plan 3 carry out your plan 4 examine the solution Sh Algorithm 1 Algorithm 1 we will consider 2 different designs for solving this problem When YOU reach the end of the line the name and Finding the oldest person algorithm 1 bgtheday of the oldest person Will be written on the 1 line up all the people along one wall D p 2 ask the first person to state his or her name and biithday Q then write this information down on a piece of paper 0 g 0 3 for each successive person in line I I l l I I i ask the person for his or her name and birthday g V 33230211302024irisrinrggastritis 320 it rim are Err ofthis person 021220 0210050 0030050 000050 00020 0000 003050 000030 8482 i 8482 83812 53 5332 when you reach the end of the line the name and birthday v 10 107 105950 101720 1 0 L 0 of the oldest person will be written on the paper 1 10 2680 2 680 2282009 Algorithm 2 I Algorithm 2 when there is only one person left in line that person Finding the oldest person algorithm 2 is the odest 1 line up all the people along one wall o o O 2 as long as there is more than one person in the line repeatedly mm 1 mVi iim i have the people pair up 1st with 2 3rd with 4 etc if k c 39 there is an odd number of people the last person will be 39H In 39H In without a partner u ask each pair of people to compare their bilthdays 1 m request that the younger of the two leave the line In I when there is only one person left in line that person is i l l the oldest Algorithm Analysis Algorithm Analysis determining which algorithm is quotbetterquot is not algorithm 1 involves asking each person s birthday and always clear cut then comparing it to the birthday written on the page it depends upon what features are most important to the amount of time to find the oldest person is proportional you to the number of people if you are concerned about development time choose the if you double the amount of people the time needed to find algorithm that is easiest to implement the oldest person will also double if you care about the time to run the program you need to analyze performance Algorithm Analysis cont when the problem size is large performance differences can be V Algorithm Analy5s dramatic for example assume it takes 5 seconds to compare bilthdays for algorithm 1 100 people 9 5100 500 seconds algorithm 2 allows you to perform multiple comparisons 200 people 9 5200 1000 seconds simultaneously 400 people 9 5400 2000 seconds the time needed to nd the oldest person IS proportona to N MN the number of rounds it takes to shrink the hne down to one 1000000 people 9 51000000 5000000 seconds person I 9 which turns out to be the logarithm base 2 of the number of for algorlthm 2 00 10 people 100 people 9 5i log2 100 i 35 seconds 1900 11 if you double the amount of people the time needed to nd 200 People 9 5r 39092 200 i 40 seconds 40000 e 400 people 9 5i log2 400 i 45 seconds 3 the oldest person increases by the cost of one more comparison H l 1000000 people 9 5f log2 1000000 l 100 seconds 1010000 20 Algorithm Analysis cont when the prob c lem size is large performanoe differences be dramatic 1000000 people gt 51000000 5000000 seconds or 57 days 1000000 people gt 5l log2 1000000 39l 100 seconds or 16 minums 2282009 5 Big Oh Notation to represent an algorithm s performance in relation to the size of the problem computer scientists use what is known as Ely0h notation executing an ON algorithm requires time propo tional to the size ofpro e given an ON algorithm doubling the problem size doubles the work executing an Olog N algon39thm requires time propor 1 Big h Notation based on our previous analysis algorithm 1 is classi ed as ON algon39thm2 is Olog N Another Algorithm Example there are two commonly used algorithms for searching a list of items sequential search general purpose but relatively slow binary search restricted use but fast extltem in the ll lfyou reach the end of the list and have not found the item then ltwas not in the list tio al to the logarithm of the problem size given an Olog N algorithm doubling the problem size 5 a constant amount of work 1 Another Algorithm Example 5 CHING a common problem in computerscienoe involves st ri g and mai taining large amounts of data and then searching the data for particularvalues da storage and retrieval are key to many industry applications search algorithms are necessary to storing and retrieving data efficientl eg consider searching a large payroll database for a particular reco if the compumr selected entr ies at random there is no asiirance that the particular record will be found even if the record is found it is likely to take a large amount of time that it will be found more efficiently Sequential Search nt739aseac1 is an algorithm that involves examining each list item in sequential order until the desired item is fo eguential Search for nding an imm in a list i e st examine the item 7 it that item is the one you are seeking then you are done is not the item you a e seeking then go on to the n sequential search guarantees that you will fnd the item if it is in t e list but it is not very practical for very large databa warstcase you may have to look at every entry in the list Binary Search binaysearch involves continually cutting the desired search list in half until the item is found the algorithm is only applicable if the list is ordered eg a list of numbers in increasing order eg a list of words in alphabetical order binary search for finding an item in an ordered list initially the potential range in which the item could occur is the entire list as long as items remain in the potential range and the desired item has not been found repeatedly examine at the middle entry in the potential range if the middle entry is the item you are looking for then you are done if the middle entry is greater than the desired item then reduce the potential range to those entries left of the middle if the middle entry is less than the desired item then reduce the potential range to those entries right of the middle by repeatedly cutting the potential range in half binary search can hone in on the vwv Ciuicklv Equot Equot 2 2282009 Binary Search Example suppose you have a sorted list of state names and want to find Illinois 1 start by examining the middle entry Missouri since Missouri comes after Illinois alphabetically can eliminate it and all entries that appear to the right 2 next examine the middle of the remaining entries Florida since Florida comes before Illinois alphabetically can eliminate it and all entries that appear to the left 3 next examine the middle of the remaining entries Illinois the desired entry is found H Alain ama HAlaska iiCanfomialimo dahnawa HnunoisHIowaH Missouri HNebmskaH Nevada Ohioiimegonii Tennessee Texas Washington Z 3 4 5 6 7 S 9 10 ll 12 13 14 15 1 ell mid right il il 1 Il lm s llr llu llm L i lln 1 ll L39 H H 397 H1quot H x L H HAiabama H H H H H H m Hm m MM H H H I m H m H v mans a H 1 3 4 s e s 9 m 1 12 13 14 is left and right i H i i ll V39 ll lm llr ll u llm L H r a ll i ll H 39r H1quot H x l l l a all ll ii II ii ll ll quot ll V b H quot ll iI ll H H a l l l 3 4 5 l 7 8 9 10 ll 12 13 14 15 ell mid right Search Analysis sequential search in the worst case the item you are looking for is in the last spot in the list or not in the list at all as a result you will have to inspect and compare every entry in the list the amount of work required is proportional to the list size 9 sequential search is an ON algorithm binary search in the worst case you will have to keep halving the list until it gets down to a single entry each time you inspectcompare an entry you rule out roughly ha f the remaining entries the amount of work required is proportional to the logarithm of the list size 9 binary search is an Olog N algorithm Search Analysis imagine searching a phone book of the United States 300 million people sequential search requires at most 300 million inspectionscomparisons binary search requires at most log2300000000 29 inspectionscomparisons Chapter 9 continued Abstraction and UserDefined Functions 3232009 Multiple Inputs ifa function has more than 0 input parameters in the function definition are separated by commas input values in the function call are separated by commas valus are matched to parameters by or er 1St input value in the function call is assigned to the 1St parameter in the function 2rid input value in the fun pa am ction call is assigned to the 2rid eter in the function Multiple Inputs function OldMacVerse animal n displays esp MacDonald v OldMacVerse quotco mg OldMacVerse quotmooquot vicowvi I Parameters and Locals parameters play an important role in functions they facilitam the creation of generalized computations ie the function defines a formula but certain values within the formula can differ each time the function is called technically a parameter is a local Vanishe meaning it exists only inside its particular function when the functi n is called memory cells are allocated for the aramet rs and each input from the call is assigned to its corresponding parameter nce a parameter has been assigned a value you can refer t r Parameters and Locals by default variables other than parameters are considere 9 ob l meaning they exist and can be acoessed by JavaScn39pt oode anywhere in the page o it is possible to use the same name to refer to a local variable and a global variable within the function the local variable is acc ssible e outside that function the global variable is accessible th 0 that paramete within the function ust as y u would any other variable when the function mrminates the paramemrs go awayquot and eir associamd memory cells are freed Declaring Local Variables we have seen that variables are useful forston39ng intermediate steps in a oomplex computation within a userrdef39ned nction the programmer is free to create new variables nd se them in specifying the fun tlon39s computation however by default new var iables used in a function are global t Mistithe same vanabe names aready used ysewhere I f 394 q39 4 flu enigmay Vanishes to be local fab ac ab39an is a safe merit that lists all local Varables u used in a mncobn usually the rst statement in a Imcb39an general form Var DEAL LDC412 Al n 3232009 I Declaring Local Variables I Functions with Return function IncomeTaXincome itemized I Assumes income gt 0 itemized gt 0 displaying results usmg document write or alert is Results displays flat tax 13 due after for some functions deductions for full generality we need to be able to return an output value which can then be used in other computations var deduction taxableIncome totalTaX eg number Mathsqrt9 deduction Mathmaxitemized 4150 taxableIncome Mathmaxincome deduction 0 totalTaX 0 13taxablelncome amountOwed IncomeTaX38000 6500 alert quotYou owe squot totalTax a return statement can be added to a function to specify gt its output value since these variabes are dedared as Ocal they win when the return statement is reached the variable or expression not affect or be affected by any variables with the is evaluated and Its value is returned as the functions output general form return OUTPUTVALUE same names elsewhere in the page e umms kliPra39turss mm niiunirau p i391siiis quot3rTm if the same computation I FU Wlth i quoti Tm must be done repeatedly 3 V quot a function can greatly l 39 simplify the page function IncomeTaXincome itemized j I here FahrToCelsius iS Assumes income gt 0 itemized gt 0 called twice to convert Returns flat tax 13 due after deductions two different temperatures var deduction taxableIncome totalTaX deduction Mathmaxitemized 4150 taxableIncome Mathmaxincome deduction 0 TemperatureConversionPage totalTaX 0 13taxab1eIncome LII paratuie conversion Page ii Dam 1m 457 1 1th mhhrmmo return totalTaX 3339 39 Spiritgiiiizttizszi Leipzig 252121 ziiz l l 2 rquot it 7 7 Dam u zzama say since this function returns the value it can be used in other quot quotquot quotquot quot 39 computations eg calculate amount owed in 4 payments 3 gg l g7322313Rhinililtiix 2132 tilri payment IncomeTaX 38000 6500 4 I De5igning Functions I DeSIgning Functions functions do not add any computational power to the when is it worthwhile to define a function language if a particular computation is complex meaning that it a function definition simply encapsulates other statements requires extra Variables and0r multiple lines to define still the capacity to define and use functions is key to if y0u have to perform a particular computation repeatedly solving complex problems as well as to developing W39th39 a page reusable code encapsulating repetitive tasks can shorten and simplify code I When CiEfinii iQ a iiUi iCtiOI i YOU mUSt identify functions provide units of computational abstraction the inputs programmer can ignore details the computation to be performed using those inputs functions are selfcontained so can easily be reused in the output different applications 3232009 Design Example consider the task of designing an online Magic 8ball Mattell Inc must be able to ask a yesno type question USI ng a JavaSCl l Ilbl al y receive an answer presumably at random C 39d use Put JavaScript functions in a separate file with a js mg a text area for entering extension l imifgwiglill lm il v 7 X r l 0 the queStion 4 A v could be several lines Include the code using the src attribute in a script tag Aegicsmii ulna long Magic S39bau a text box for Enter your quesriouin the text area below d isp layi n 9 th e a n swer which should be short Do not put anything between the opening and closrng a button for initiating scri t ta 5 the action which p g m Ifnvolves calling a h The code In the functionsJs file Will be added msrde the unction to processt e question select an scrlpt tags Done Hiozalmanet mumz v answer and in the text box if Magic 8rball rWindaws linemet Bplorer ltscript typequottextjavascriptquot srcquotfunctionsjsquotgtltscriptgt 39i r 52 ici 52225 1 l The Magi Sba 5m llilgl ly unlikely Using randomjs in the page below the random js library is accessed via the Web you can download the le and store it on your own machine 7 then simply specify the file name in the SRC attribute the default is that the file is in the same folder as the Web page that includes it randomjs The random j 5 library contains useful functions for generating random e valu s l hull 2 l7 up mil ave reed 7 a me pane uses mumm a l lvl and rimlav a raina minir I 1mnlnn InpllIs Umpm T f f ESP TesLWinnowsimernerapiorer RandomNuIn Two numbers low and high hnnis of A random numher from he i ritl MR araiigercgRandomNumi2 45 alngIUWHIICIIKWQ10mg 2 M 135113 ii no mam lS 5 wm Vl 3 lei l 9quot exclusive w it lt9 lr ESPTest l Mme v 11 Sr HIE wit ymaw WV 7 Randonitnt Two integers low and high limits of A random integer from the range 1 gunman Hemmer lo row in high born immune h t Results dismay e randvn number m lesseeem RandomChar A nmieixlprysiruigeg A random character taken from 1539 var Wan Mvnumberwasz Were vuucmrecn l 5 Ra dm hari ab R r W a Randomoneof A llSl 01 options in brackets separated A random value taken lrom he Daria tamlinnanet Kl lu v In CHHIHHSLtEu lisi of options I dommntqet enent yldt messay ox39value 39 in n u in 10 quotMy nunbzr has quot Number quot were you CDTFECtT Randomoneof yes no Ii 11 I g Jig10 note the RandomOneOf 1 I to load a library of functions in a page use a pair of SCRIPT tags 3 gwwmmwnw functlon from random 15 u an weeWearrenew or m i a 3 mquot arequot would Similarly be useful ltscript typequottextjavascriptquot srcquotrandomjsquotgt 4 hmquot WWW i W immune4 mew for the MaQIC 8 ball Page lt5Crlptgt j ggg in selecting possible as In answers at random Errors to Avoid Errors to Avoid When beginning programmers attempt to load a JavaScript 2 when you use the SRC attribute in a pair of SCRIPT tags to code library errors of two types commonly occur load a code library you cannot place additional JavaScript code between the tags L if the SCRIPT tags are malformed or the nameaddress of the a think of the SRC attribute as causing the contents of the library to be inserted between the tags overwriting any other code that library IS incorrect the library wrll fail to load was erroneously placed there a this will not cause an error in itself but any subsequent attempt to call a function from the library will produce ltscript typequottext jaVaSCIipt quot srcquotFILENAMEquotgt ANYTHING PLACED IN HERE WILL BE IGNORED ltscriptgt quotError Object Expected using Internet Explorer or quotError XXX is not a function using Firefox where XXX is the entered name a if you want additional JavaScript code or another library you must use another pair of SCRIPT tags 3182009 g Simplifying buttons g Simplifying buttons COHSider the button from greetboxhtml functions provide a mechanism for simplifying complex input typequotbutton vaiuequotclick for Greetingquot bUttons SUCh as thls onclickquoti39ir stllame ulruumentgetElementEyIdf39fi rstl vlarneE itnzx 39iusa39lue lastilame lanculnentxjetEl eriieritEtr39ltlij lastllanieEulsquot I value message 39Hello fir stllame 39 lastllame I reca from Chapter5 39 or may I just call you quot firstllame 39 quotlieu Ilaugnultln aquott be related tnFtnhe lastllame I we USECI DFEdEfII39IEd JavaScrIpt fUl lCthl lS to accomplish 395 Failquot i39me quotquot z39l L39H 39 some of the work that needed to be done IllIulnent getEl ementEWItl quotme ssagehrea quot xval ue message quot a Mathrandom I I Mathfloor 39 311 scl ig lmi enadcllck attnbute makes the button complex functions reduce the length and complexity of code eg a single call to Math sqrt replaces the underlying plus must be careful with nested quotes vs complex algorithm Sim le userdefined functions Sim le userdefined functions in addition to JavaScript39s predefined functions the user a function definition begins with the word function can define new functions in the HEAD section and call followed by its name and them Within the Page a function name should be descriptive of the task being performed W th mmm mm lines beginning with are comments that describe the H Assumes DESCRIPTION or ANY ASSUMPTIONS AB DU39li il39llE PAGE function39s b6haVi0r in Results plESthPirtoN or hit ACTION eeeroemeo B r lE FUNCTION comments are ignored by the interpreter but make code STATEMENTSTDBEExECUTEp more userreadable the statements to be executed when the function is called are placed between the curly braces lrllelgreetDoMthl Dave Reed COde from This page displays a personalized greeting in a text area 2 userde ned Greet 3 function ilrstllame ox and lastllame ox contain names a writes a message with those names in messageArea Mead ztitie Long Greeting titles 9 scri pt ty39pe texr 39javastript erquoti v r L 39 Ll lame LlIZlCLllIlll llttElelllelltg lltltnfll STZNElIIlF 139 lastllame documentgetEiementEyItIr39 iastllan 17 message Hello quot firstName quot quot iastNai ae 13 or may I just caii you quot firstllame 19 quot739 You 39 be I to the iastllame 20 quots of Parl Mei e 39 i Chapter 9 Abstraction and UserDefined Functions 2 documentgetEiementByIdc messageh eaW vai ue message 34 mscript 2 h 39aquot 2quot body peEEer your first name dnput truestext idquotfirstNameBmquot sizequot15 v 31 Enter your last name Ainput typequottextquot 1d laStMameBDquot sizequot15quot a 32 1nput type text id fahrl3m size 1039 vaiuequotquot l more than one quot39 39 statement is to be associated with a piItextaraa id39nessaeAreaquot rM squot4quot cols 4quot utextarea a bocljv separate function 41 htlnl I p gr input twpe button valuequotiiick for Greetingquot onclickquotGiquoteetI 3quot A 1 3182009 Abstraction abshac 39on is the procss of ignoring minutiae and focusing on the big picture in modern life we are constantly confronted with complexity we don39t necessarily know how it works but we know how to it eg how does a TV work a car a computer we survive in the face of complexity by abstracting away details to use a TVcarcomputer it39s not important to understand the inner workings we ignore unimportant details and focus on those features relevant to using it eg TV has power switch volume control channel changer Abstraction JavaScript functions like Mathsqrt provide computational abstraction a function encapsulates some computation amp hides the details from the programmer the programmer only needs to know how to call the function not how it works General Function Form to write generalpurpose functions we can extend de nitions to inclu e return statements function FUNCTIONNAMEPARAMETELL PARAMETERJ PARAMHELH Assumes DESCRIPTION oE ASSUMPTIONS MADE ABOM PARAMETERS Returns DESCRIPTION OF VALUE RETukNED BY EuNnmN var LDCALJ LDCALZ LOCALJ optional sTATEMENTsJoJEREoRMJHE uEsIREucoMPuTAUoN return ouTPuLvALuE optional General Function Form parametersare variables that correspond to the function s inputs if any parameters appear in the parentheses separated by commas local va abesare temporary variables that are limited to that function only if require some temporary storage in performing calculations then declare local variables using the keyword Var separated by commas a local variable exists only while the function executes so no potential con icts with other functions a return statementis a statement that speci es a value to be returned from the function consists of the keyword return followed by a variable or expression General Function We will be working with functions that get information from text boxes or text areas We will be working with functions that display their results in text boxes or text areas function FUNCTIONNAME Description of what the function does STATEMENTSTOPERFORMDESIREDTASK Examples Let39s try it 182009 l Viewing Web Pages You are used to looking at web pages in a 5 What IS a Web Page browser Web pages are plain text files These files can be viewed in a variety of applications Viewing Web Pages What is plain text What it looks like in a text editor vs what it 39 N t a word document looks like in the browser Not a rtf file The extension does not define what is in the file Has text only No hidden formatting Plain text editors with syntax Plain text editors highlighting Need to use a plain text editor For developing web pages it is great to have some Windows has one built in help There are many plain text editors that provide notepad syntax highlighting PSPad Mac has textEdIt but It IS not a plain text editor httpwwwpspadIcomendownload39php You can change the settings so it works like a plain text TextWrangler Editor G0 to httpwwwbarebonescomproductsTextWranglerdownloadhtml httpsupportapplecomkbTA20406viewlocaleenUS for instructions 182009 Accessing Local Files HTML Open in text editor The language of the web a Open in web browser Not a programming language Markup language simply defines how to display the content l Web Page Web Page I Content Content What is to be dismayed on the actual page a What is to be displayed on the actual page Structure Structure I a How it is to be interpreted How it is to be interpreted I Making it look good Julr e l7 dem1html rme Need 7 This is a simple web page H ltl 7 77777 1 3 4 5 C mead 7 rtitle Title of the Page quotINVHH Textthmappeaxsmdiepage l Mead 9 M1 bodva 1 up Text that appears in the page lt pgt 12 39bcmygt Beginning a web page Content Decide what you want the web page to This step will not look like a web page contain a Don39t be surprised when it does not resemble Decide what you want it to look like your picture Draw a picture Remember you are making decisions about this will be your guide the actual content only can later add or take away parts Later you will add structure and style 5 Content Put notes in the content to keep track of what you want it to be For lists or tablesjust add a note in parenthesis this is a list or simply list this is a table or simply table For heading specify a general size small heading large heading medium heading Content For links include the part that will be displayed in the web page without parenthesis Add the actual link information in parenthesis To see the catalog Click Here link to httpwwwusueduregistrarcatalogpdfl Find more information go to USU39s web site link to httpwwwusuedu 182009 Content For images make a note that includes the actual filename and location Picture ofa tree treejpg Picture ofapplication form imagesapplicationgif Picture ofa cottage quotn Make the description meaningful Content You may want to have an image that is a link This is called a graphic link Add both the image information and the actual link information in parenthesis Hcture ofa tree treejpg link to httpwwwarbordayorg Hcture ofa ootta e httpwwwartbythomaskinkadeoom magskinkade foxgloveCottagijpg link to httpwwwleisuredirectionooukukoottagessouth england Content Do this step in plain text Name the file the same thing you are going to name the web page le This is actually the beginning of the page and we will add to it to complete the web page nanosheetshtm Example Let39s begin a web page nanotech sheets Picture Content


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Jennifer McGill UCSF Med School

"Selling my MCAT study guides and notes has been a great source of side revenue while I'm in school. Some months I'm making over $500! Plus, it makes me happy knowing that I'm helping future med students with their MCAT."

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.