Download presentation
Presentation is loading. Please wait.
1
Chapter 1 Computer Basics
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 1 Computer Basics
3
What is a Computer? a computer is a device that receives, stores, and processes information different types of computers have different characteristics supercomputers: powerful but expensive; used for complex computations (e.g., weather forecasting, engineering design and modeling) desktop computers: less powerful but affordable; used for a variety of user applications (e.g., , Web browsing, document processing) laptop computers: similar functionality to desktops, but mobile palmtop computers: portable, but limited applications and screen size
4
Desktop Specifications
purchasing a computer can be confusing sales materials contain highly technical information and computer jargon the following specs describe two computer systems for sale in January, 2007 Desktop 1 is a low-end system, inexpensive but with limited features Desktop 2 is a high-end system, uses the latest technology so expensive
5
Hardware vs. Software the term hardware refers to the physical components of a computer system e.g., monitor, keyboard, mouse, hard drive the term software refers to the programs that execute on the computer e.g., word processing program, Web browser hardware components software components
6
Common Desktop Hardware
7
von Neumann Architecture
although specific components may vary, virtually all modern computers have the same underlying structure known as the von Neumann architecture named after computer pioneer, John von Neumann, who popularized the design in the early 1950's the von Neumann architecture identifies 3 essential components Input/Output Devices (I/O) allow the user to interact with the computer Memory stores information to be processed as well as programs (instructions specifying the steps necessary to complete specific tasks) Central Processing Unit (CPU) carries out the instructions to process information
8
Central Processing Unit (CPU)
the CPU is the "brains" of the computer, responsible for controlling its inner workings made of circuitry – electronic components wired together to control the flow of electrical signals the circuitry is embedded in a small silicon chip, 1-2 inches square despite its small size, the CPU is the most complex part of a computer (CPU circuitry can have 100's of millions of individual components) commercial examples: Intel Core 2 Duo, AMD Athlon, Motorola PowerPC G4
9
CPU (cont.) the CPU works by repeatedly fetching a program instruction from memory and executing that instruction individual instructions are very simple (e.g., add two numbers, or copy this data) complex behavior results from incredible speed a 2.53 GHz Celeron D processor can execute 2.53 billion instructions per second a 2.93 GHz Core 2 Duo processor can execute 2.93 billion instructions per second
10
Memory memory is the part of the computer that stores data and programs modern computers are digital devices, meaning they store and process information as binary digits (bits) bits are commonly represented as either 0 or 1 bits are the building block of digital memory by grouping bits together, large ranges of values can be represented
11
Memory (cont.) memory capacity is usually specified in bytes
a byte is a collection of 8 bits – so can represent a range of 28 = 256 values large collections of bytes can be specified using prefixes since a byte is sufficient to represent a single character, can think of memory in terms of text a kilobyte can store a few paragraphs (roughly 1 thousand characters) a megabyte can store a book (roughly 1 million characters) a gigabyte can store a small library (roughly 1 billion characters) a terabyte can store a book repository (roughly 1 trillion characters)
12
Memory (cont.) modern computers use a combination of memory types, each with its own performance and cost characteristics main memory (or primary memory) is fast and expensive data is stored as electric signals in circuitry, used to store active data memory is volatile – data is lost when the computer is turned off examples: Random Access Memory (RAM), cache secondary memory is slower but cheaper use different technologies (magnetic signals on hard disk, reflective spots on CD) memory is permanent – useful for storing long-term data examples: hard disk, floppy disk, compact disk (CD), flash drive
13
Memory (cont.) higher-end computers tend to have
more main memory to allow for quick access to more data and programs more secondary memory to allow for storing more long-term data
14
Input/Output (I/O) input devices allow the computer to receive data and instructions from external sources examples: keyboard, mouse, track pad, microphone, scanner output devices allow the computer to display or broadcast its results examples: monitor, speaker, printer
15
Software recall: hardware refers to the physical components of computers software refers to the programs that execute on the hardware a software program is a sequence of instructions for the computer (more specifically, for the CPU) to carry out in order to complete some task e.g., word processing (Microsoft Word, Corel WordPerfect) e.g., image processing (Adobe Photoshop, Macromedia Flash) e.g., Web browsing (Internet Explorer, Mozilla Firefox)
16
Operating Systems the Operating System (OS) is a collection of programs that controls how the CPU, memory, and I/O devices work together it controls how data and instructions are loaded and executed by the CPU it organizes and manages files and directories it coordinates the CPU, memory, and I/O devices most modern OS's utilize a Graphical User Interface (GUI) to make interacting with the computer easy GUI's utilize windows, icons, menus, and pointers
17
Quick Net & Web Overview
the Internet is a vast, international network of computers the physical connections between computers vary, but the overall effect is that computers around the world can communicate and share resources the Internet traces its roots back to 1969, when the U.S. government sponsored the first long-distance computer network starting with only 4 computers, the network would eventually evolve into today's Internet the World Wide Web is a collection of software that spans the Internet and enables the interlinking of documents and resources the basic idea for the Web was proposed by Tim Berners-Lee in 1989 his system interlinked documents (including multimedia elements such as images and sound clips) over the Internet through the use of well-defined rules, or protocols, that define how they are formatted, documents could be shared across networks on various types of computers
18
Internet ≠ World Wide Web
the Internet could exist without the Web and did, in fact, for many years (applications included and news groups) the Web couldn't exist without the Internet the Internet is the hardware that stores and executes the Web software
19
Viewing a Web Page a Web page is a text document that contains additional formatting information in a language called HTML (HyperText Markup Language) a Web browser is a program that accesses a Web page, interprets its content, and displays the page
20
Web Addresses a Web server is an Internet-enabled computer that stores Web pages and executes software for providing access to the pages when you request a Web page, the browser sends a request over the Internet to the appropriate server the server locates the specified page and sends it back to your computer Web pages require uniform names to locate and identify them uniquely each page is assigned a Uniform Resource Locator (URL) URL's are commonly referred to as Web addresses the different parts of the Web address provide information for locating the page
21
Viewing Local Web Pages
a Web browser can be used to view pages stored on the same computer can go through the File menu to select the local page, or can enter the File location in the address box (without the http prefix) this feature is handy when developing Web pages can create a Web page and view it in the browser before uploading to a server
22
Chapter 2 HTML and Web Pages
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 2 HTML and Web Pages
24
HTML & Web Pages recall: a Web page is a text document that contains additional formatting information in the HyperText Markup Language (HTML) HTML specifies formatting within a page using tags in its simplest form, a tag is a word or symbol surrounded by brackets (<>)
25
HTML Tags required tags in a Web page:
<html> and </html> enclose the entire HTML document the HEAD section (enclosed between <head> and </head>) contains information that the browser uses to control the look of the page the HEAD can contain a title for the browser window, enclosed between <title> and </title> the BODY section (enclosed between <body> and </body>) contains the text that will appear in the page
26
HTML Elements tags and the text they enclose form an HTML element
<title> Title of the Page </title> is a TITLE element <head> <title> Title of the Page </title> </head> is a HEAD element (which contains a nested TITLE element) most HTML elements have opening and closing tags, but not all <!-- demo1.html Dave Reed --> is a COMMENT element a comment is ignored by the browser (it does not appear in the rendered page) comments are used by the page developer to document page features
27
Text Layout white space (extra spaces, tabs and blank lines) are ignored by the browser this allows the browser to adjust the text to the window size you can control some of the text layout using HTML elements a PARAGRAPH element (<p>…</p>) specifies text surrounded by blank lines a BREAK element (<br />) causes text to be displayed on a new line the symbol forces a space to appear in the text
28
Headings & Alignment in a large document, it is useful to divide the text into sections and then provide each with a heading describing the content that follows <h1> … </h1> enclose a top-level heading (large and bold) <h2> … </h2> enclose a sub-heading (slightly smaller and bold) . . . <h6> … </h6> enclose the smallest sub-heading the HORIZONTAL-RULE element <hr /> draws a dividing line in the page by default, headings and other elements are left-justified in the page can change the alignment of an element by adding a style attribute that qualifies the appearance of the element <h1 style="text-align:center"> Centered Heading </h1> <p style="text-align:right"> This paragraph is right justified. Each line will be shifted to line up at the right margin. </p>
29
Headings & Alignment (cont.)
the DIV element groups multiple elements, so can be formatted together
30
Font Formatting text can be formatted in a variety of ways
bold (<b> … </b>), italics (<i> … </i>), underlined (<u> … </u>) colored text is enclosed in <span style="color:????"> … </span> common colors can be used (e.g., red, green, orange, light blue, dark blue)
31
Hyperlinks a hyperlink, or just link, is a connection to another Web page by default, a link appears as underlined text in the page when the user clicks on the link, the corresponding page is retrieved and displayed a link is specified using ANCHOR tags <a> and </a> text that appears within the tags is displayed as the link in the page must have an HREF attribute that specifies the associated Web address <a href=" University</a> <a href="personal.html">Local Page</a> note: the browser displays links underlined and in color by default, links whose pages have not yet been visited are blue by default, links whose pages have previously been visited are purple
32
Hyperlinks (cont.)
33
Images Web pages can contain other types of media besides text and links images are embedded in a page using an IMG tag ( <img /> ) similar to <br /> and <hr />, there is no closing tag so it ends with a slash IMG attributes SRC specifies the location of the image file ALT specifies alternate text that is displayed if the image fails to load
34
Lists HTML lists organize items in sequence
<ul>…</ul> enclose an unordered list; <ol>…</ol> enclose an ordered list <li>…</li> enclose a list item
35
Lists (cont.) a style attribute can be used to format the list elements
36
Tables text can be aligned into rows and columns using a TABLE element
<table> and </table> encapsulate the table data <tr> and </tr> encapsulate a row within the table <td> and </td> encapsulate table data within a row (i.e., a column entry)
37
Tables with Borders borders can be added to tables using the border attribute the numeric value assigned to the attribute specifies thickness
38
Tables for Alignment tables are commonly used to align elements in the page here, an image is aligned to the left of some text
39
Chapter 3 The Internet and the Web
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 3 The Internet and the Web
41
History of Internet recall: the Internet is a vast, international network of computers the Internet traces its roots back to the early 1960s MIT professor J.C.R. Licklider published a series of articles describing a “Galactic Network” of communicating computers in 1962, Licklider became head of computer research at the U.S. Department of Defense’s Advanced Research Project Agency (ARPA) in 1967, Licklider hired Larry Roberts to design and implement his vision of a Galactic Network the ARPANet (precursor to the Internet) became a reality in 1969 it connected computers at four universities: UCLA, UCSB, SRI, and Utah it employed dedicated cables, buried underground the data transfer rate was 56K bits/sec, roughly the same as dial-up services today the ARPANet demonstrated that researchers at different sites could communicate, share data, and run software remotely
42
ARPANet the 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
43
ARPANet Growth by 1980, close to 100 sites were connected to the ARPANet satellite connections provided links to select cities outside the continental U.S.
44
NSFNet in the early 1980s, the ARPANet experienced an astounding growth spurt applications such as , newsgroups, and remote logins were attractive to all colleges and universities by 1984, the ARPANet encompassed more than 1,000 sites to accommodate further growth, the National Science Foundation (NSF) became involved with the ARPANet in 1984 NSF funded the construction of high-speed transmission lines that would form the backbone of the expanding network
45
"Internet" the term “Internet” was coined in recognition of the similarities between the NSFNet and the interstate highway system backbone connections provided fast communications between principal destinations, analogous to interstate highways connected to the backbone were slower transmission lines that linked secondary destinations, analogous to state highways local connections were required to reach individual computers, analogous to city and neighborhood roads note: Al Gore did not INVENT the Internet, nor did he ever claim to he sponsored legislation in the late 1980s to support growth and expand access recognizing that continued growth would require significant funding and research, the government decided in the mid 90s to privatize the Internet control of the network’s hardware was turned over to telecommunications companies and research organizations (e.g., AT&T, Verizon, Qwest, Sprint) research and design are administered by the Internet Society
46
Internet Society Internet Society is an international nonprofit organization (founded in 1992) it maintains and enforces standards, ensuring that all computers on the Internet are able to communicate with each other it also organizes committees that propose and approve new Internet-related technologies and software
47
Internet Growth until recently, the Internet more than doubled in size every 1 or 2 years why has this trend slowed? will it continue? (“Internet Domain Survey.” Internet Software Consortium, July 2006.)
48
Distributed Networks the design of the ARPANet was influenced by the ideas of Paul Baran, a researcher at the RAND Institute Baran proposed 2 key ideas: distributed network and packet-switching recall: the ARPANet was funded by the Dept of Defense for communications as such, it needed to be resistant to attack or mechanical failure
49
Packet Switching in a packet-switching 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
50
Advantages of Packets sending information in smaller units increases the efficient use of connections large messages can't monopolize the connection analogy: limiting call lengths at a pay phone to limit waiting transmitting packets independently allows the network to react to failures or network congestion routers (special-purpose computers that direct the flow of messages) can recognize failures or congestion and reroute the packet around trouble areas 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
51
Protocols and Addresses
the Internet allows different types of computers from around the world to communicate this is possible because the computing community agreed upon common protocols (sets of rules that describe how communication takes place) the two central protocols that control Internet communication are: Transmission Control Protocol (TCP) Internet Protocol (IP) these protocols rely on each computer having a unique identifier (known as an IP address) analogy: street address + zip code provide unique address for your house/dorm 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 each computer is assigned an IP address by its Internet Service Provider (ISP) some ISPs (e.g., AOL, most colleges) maintain a pool of IP addresses and assign them dynamically to computers each time they connect
52
TCP/IP Transmission Control Protocol (TCP) Internet Protocol (IP)
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
53
Routers and DNS the Internet relies on special purpose computers in the network routers are computers that receive packets, access the routing information, and pass the packets on toward their destination domain name servers are computers that store mappings between domain names and IP addresses domain names are hierarchical names for computers (e.g., bluejay.creighton.edu) they are much easier to remember and type than IP addresses domain name servers translate the names into their corresponding IP addresses
54
History of the Web the World Wide Web is a multimedia environment in which documents can be seamlessly linked over the Internet proposed by Tim Berners-Lee at the European Laboratory for Particle Physics (CERN) in 1989 designed to facilitate sharing information among researchers located all over Europe and using different types of computers and software Berners-Lee's design of the Web integrated two key ideas hypertext (documents with interlinked text and media) Web pages can contain images and links to other pages the distributed nature of the Internet pages can be stored on machines all across the Internet, known as Web servers logical connections between pages are independent of physical locations
55
Web Timeline in 2005, Google indexed more than 8 billion Web pages
1990: Berners-Lee produced working prototypes of a Web server and browser 1991: Berners-Lee made his software available for free over the Internet 1993: Marc Andreesen and Eric Bina of the University of Illinois’ National Center for Supercomputing Association (NCSA), wrote the first graphical browser: Mosaic Mosaic integrated text, image & links, made browsing more intuitive 1994: Andreesen founded Netscape, which marketed the Netscape Navigator 1995: Microsoft released Internet Explorer the browser wars begin! 1999: Internet Explorer becomes the most popular browser (~90% of market in 2002) 2006: Mozilla Firefox (Netscape descendent) grows in popularity, IE share drops to 80% in 2005, Google indexed more than 8 billion Web pages other sources estimated more than 25 billion Web pages (“Internet Domain Survey.” Internet Software Consortium, July 2006. “Netcraft Web Server Survey.” Netcraft, July 2006.)
56
How the Web Works like Internet communications, the Web relies on protocols to ensure that pages are accessible to any computer HyperText Markup Language (HTML) defines the form of Web page content HyperText Transfer Protocol (HTTP) defines how messages exchanged between browsers and servers are formatted the prefix in a URL specifies that the HTTP protocol is to be used in communicating with the server the prefix is NOT used for local file access since no server communication is necessary for efficiency reasons, browsers will sometimes cache pages/images to avoid redundant downloads, the browser will store a copy of a page/image on the hard drive (along with a time stamp) the next time the page/image is requested, it will first check the cache if a copy is found, it sends a conditional request to the server essentially: "send this page/image only if it has been changed since the timestamp" if the server copy has not changed, the server sends back a brief message and the browser simply uses the cached copy
57
Chapter 4 JavaScript and Dynamic Web Pages
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 4 JavaScript and Dynamic Web Pages
59
Static vs. Dynamic Pages
recall: a Web page uses HTML tags to identify page content and formatting information HTML can produce only static pages static pages look the same and behave in the same manner each time they are loaded into a browser in 1995, researchers at Netscape developed JavaScript, a language for creating dynamic pages Web pages with JavaScript can change their appearance: over time (e.g., a different image each time that a page is loaded), or in response to a user’s actions (e.g., typing, mouse clicks, and other input methods)
60
Programming Languages
JavaScript is a programming language a programming language is a language for specifying instructions that a computer can execute each statement in a programming language specifies a particular action that the computer is to carry out (e.g., changing an image or opening a window when a button is clicked) some programming languages are general-purpose popular languages include C++, Java, J# JavaScript was defined for a specific purpose: adding dynamic content to Web pages can add JavaScript statements to a Web page using the HTML tags <script type="text/javascript"> </script> when the browser displays the page, any statements inside the SCRIPT tags are executed and the result is displayed
61
Simple Dynamic Page below is a simple Web page with dynamic content
note: dynamic content can be mixed with static HTML content it demonstrates two types of JavaScript statements an assignment statement that asks the user for input and stores that input a write statement that writes text into the HTML page
62
Assignment Statement firstName = prompt("Please enter your name", "");
when an assignment statement involving prompt is executed by the browser a separate window is opened with a text box for the user to enter text when the user is done typing, he/she can click on the OK button firstName = prompt("Please enter your name", ""); when OK is clicked, the text entered is assigned to a variable a variable is a name used to symbolize a dynamic value here, the variable firstname is used to store the text entered by the user
63
Assignment Statement (cont.)
the general form of an assignment statement using a prompt is VARIABLE = prompt("PROMPT MESSAGE", ""); the variable name can vary depending on the task at hand here, the variable is used to store the user's first name, so firstName is a meaningful name the prompt message that appears in the window can likewise change here, the message "Please enter your name" tells the user what is expected
64
Write Statement when a write statement is executed by the browser
the message specified in the statement is written into the HTML page a message can include a string literal – text enclosed in quotes a variable a combination of strings and variables, connected via '+' document.write("<p>Hello " + firstName + ", welcome to my Web page.</p>"); when a variable is encountered, the browser substitutes the value currently assigned to that variable
65
Write Statement (cont.)
the general form of a write statement is document.write("MESSAGE TO BE DISPLAYED " + VARIABLE + " MORE MESSAGE" + ...); note that the statement can be broken across lines, as long as no string literal is split (i.e., the beginning and ending quotes of a string must be on same line) the pieces of the message are displayed in sequence, with no spaces in between if you want spaces, you have to enter them in the text
66
Formatted Output the output produced by a write statement is embedded in the page the browser displays this output just as it does any other text if the text contains HTML tags, the browser will interpret the tags and format the text accordingly document.write("<p>Hello <i>" + firstName + "</i>, welcome to my Web page.</p>"); assuming the variable firstName has been assigned "Dave", the browser would execute the statement to produce <p>Hello <i>Dave</i>, welcome to my Web page.</p> which would be displayed by the browser as Hello Dave, welcome to my Web page.
67
Syntax Errors yields: Error: unterminated string literal
an error in the format of an HTML or JavaScript statements is known as a syntax error some syntax errors are ignored by the browser e.g., misspelling an HTML tag name most JavaScript syntax errors will generate an error message document.write("This example is illegal since the string is broken across lines"); yields: Error: unterminated string literal document.write("The value of x is " x); yields: Error: missing ) after argument list
68
JavaScript Variables a variable name can be any sequence of letters, digits, and underscores (but must start with a letter) valid: tempInFahr SUM current_age Sum2Date x invalid: 2hotforU salary$ two words "sum_to_date" variable names are case sensitive, so Sum and SUM are treated as different variables
69
Variables & Memory Cells
computers keep track of the values that variables represent by associating each variable with a specific piece of memory, known as a memory cell when a JavaScript assignment is executed, firstName = prompt("Please enter your name", ""); the value entered by the user (e.g., "Dave") is stored in a memory cell associated with the variable firstName any future reference to the variable name evaluates to the value stored in its associated memory cell
70
Another Example once you create a variable, you can repeatedly assign values to it only the most recent value is retained in memory EXAMPLE: suppose we want to prompt the user for two different foods if only one food is needed at a time, we can reuse the same variable
71
Reusing Variables the first pair of statements
food = prompt("What is your favorite food?", ""); document.write("<p>Your favorite food is " + food + "</p>"); the first pair of statements stores the user's favorite food displays that food in the page
72
Reusing Variables (cont.)
food = prompt("What is your least favorite food?", ""); document.write("<p>Your least favorite food is " + food + "</p>"); the second pair of statements stores the user's least favorite food (overwriting the old value) displays that food in the page
73
Prompts with Defaults VARIABLE = prompt("PROMPT MESSAGE", "");
so far, all prompts have been of the form VARIABLE = prompt("PROMPT MESSAGE", ""); sometimes it makes sense to provide default values for prompts can specify a string literal instead of "" this string will appear in the prompt box when it appears if the user wants to accept the default value, can just click OK EXAMPLE: suppose we wanted to create a page that displays a verse of the children's song, Old MacDonald had a Farm the page should be able to display any verse can accomplish this by prompting the user for the animal and sound can specify default values so that it is easy to display a common verse animal = prompt("Enter a kind of animal:", "cow"); sound = prompt("What kind of sound does it make?", "moo");
74
Old MacDonald this page prompts the user for the animal and sound ("cow" and "moo", by default), then displays a verse using those values <br /> tags are embedded to break the output onto separate lines
75
Old MacDonald (cont.) the default values automatically appear in the prompt boxes the user can click OK to accept the defaults OR type new values into the prompt box
76
Old MacDonald (cont.)
77
Localizing Changes so far, we have used variables to store values read in via prompts another common use is to store values used repeatedly in a page suppose we wanted to change the spelling of the refrain in Old MacDonald ("E-I-E-I-O" "Eeyigh-Eeyigh-Oh") as is, would need to find and update all occurrences in the verse instead, could use a variable to store the refrain refrain = "E-I-E-I-O"; document.write("<p>Old MacDonald had a farm, " + refrain + ".<br />"); document.write("And on that farm he had a " + animal + ", " + refrain + ".<br />"); . . . now, to update the value in the entire verse, simply must change the assignment refrain = "Eeyigh-Eeyigh-Oh";
78
Chapter 5 JavaScript Numbers and Expressions
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 5 JavaScript Numbers and Expressions
80
Data Types each unit of information processed by a computer belongs to a general category or data type e.g., string, number, Boolean (either true or false) each data type is associated with a specific set of predefined operators that may be used by programmers to manipulate values of that type e.g., we have seen string concatenation via + similarly, standard operators are predefined for numbers addition (+), subtraction (-), multiplication (*), division (/) variables can be assigned various kinds of numerical values, including mathematical expressions formed by applying operators to numbers when an expression appears on the right-hand side, the expression is evaluated and the resulting value is assigned to the variable on the left-hand side word = "howdy" + " doo"; "howdy doo" word x = 50/4; x
81
Variables and Expressions
similarly, expressions can appear in write statements note: parentheses can be used to make sub-expression grouping explicit document.write(3 + 7); writes 10 document.write("The sum of is " + (3 + 7)); writes The sum is 10 if a variable appears in an expression, the value currently assigned to that variable is substituted
82
Number Representation
useful facts about JavaScript numbers to improve readability, very large or very small number are displayed in scientific notation: XeY represents the value X 10Y e.g., 1e24 1 1024 JavaScript stores all numbers in memory cells of a fixed size (64 bits) as a result, only a finite number of values can be represented e.g., 1e308 can be represented, but 1e309 is treated as Infinity 1e-323 can be represented, but 1e-324 is treated as 0 even within the range 1e e309, not all numbers can be represented note that between any two numbers lie infinitely more numbers! JavaScript can represent approximately 17 significant digits e.g.., can be represented exactly is rounded up to 1
83
Mixed Expressions in JavaScript, the + operator serves two purposes
when applied to numbers, + means addition when applied to strings, + means concatenation what about a mixed expression? when applied to a string and a number, the number is converted to a string (effectively, by placing quotes around it), then string concatenation is performed note: expressions involving + are evaluated left-to-right this can have consequences in the way mixed expressions are evaluated ADVICE: always use parentheses to group nested sub-expressions
84
Prompting for Numbers special care must be taken when prompting the user for number values recall that prompt always returns a string, even if the user enters only digits e.g., if the user enters 500 at a prompt, then the value "500" is returned myNumber = prompt("Enter a number", ""); document.write("One more is " + (myNumber + 1)); if the user entered 12 at the prompt, what would be displayed? the message displayed would be One more is 121 WHY? the prompt returns "12" which is stored in myNumber the parenthesized sub-expression (myNumber + 1) is evaluated first since this is a mixed expression, the number 1 is converted to "1" then concatenated the result, "121", is then concatenated to the end of "One more is " what is needed is a mechanism for converting strings of digits into numbers e.g., "500" 500, "1.314" 1.314, … this is accomplished in JavaScript using the parseFloat function
85
Functions in mathematics, a function is a mapping from inputs to a single output e.g., the absolute value function maps one number to another -5 5, -2.4 2.4, 17 17, … similarly, the parseFloat function maps strings of digits to numbers "500" 500, "1.314" 1.314, "0" 0, … from a programmer's view, a function is a "unit of computational abstraction" there is some computation required to calculate the output given the input(s) a JavaScript function encapsulates that computation and hides the details the user does not need to know how the function works, only how to apply it applying a function to inputs is known as calling the function the output of a function call is known as the return value
86
parseFloat a function call can appear anywhere in a JavaScript expression when the expression is evaluated, the return value for that call is substituted myNumber = prompt("Enter a number", ""); myNumber = parseFloat(myNumber); document.write("One more is " + (myNumber + 1)); the 1st statement prompts the user and stores their input (say "12")in myNumber the 2nd statement calls parseFloat to convert the string to a number (12) and then reassigns that number back to myNumber the 3rd statement uses the number value 12 to display One more is 13 note, the following is not an error (but probably not what was intended) myNumber = prompt("Enter a number", ""); parseFloat(myNumber); document.write("One more is " + (myNumber + 1)); the call to parseFloat returns a number, but nothing is done with that number NOTE: the only way to change the value of a variable is via an assignment statement
87
Temperature Conversion
the following page prompts the user for a temperature (in Fahrenheit), stores the input as a number, then converts that temperature to Celsius
88
Conversion Page note that the prompt has a default value of 32
89
Common Pattern many tasks that we will consider have the same basic form prompt the user for numbers store them in variables perform some calculation(s) using those numbers display the results not surprisingly, there is a pattern to the code <script type="text/javascript"> number1 = prompt("PROMPT MESSAGE", ""); number1 = parseFloat(number1); number2 = prompt("PROMPT MESSAGE", ""); number2 = parseFloat(number2); . . . numberN = prompt("PROMPT MESSAGE", ""); numberN = parseFloat(numberN); answer = SOME EXPRESSION INVOLVING number1, …, numberN; document.write("MESSAGE INVOLVING answer"); </script>
90
Predefined Functions JavaScript provides an extensive library of predefined mathematical functions Math.sqrt returns the square root of a number e.g., Math.sqrt(9) 3 Math.max returns the maximum of two numbers e.g., Math.max(3.2, 1.8) 3.2
91
Tester Page this page could be modified to test a variety of functions
change the function call in the page enter various inputs and observe the corresponding outputs
92
Other Useful Functions
Math.pow raises a number to a power Math.pow(2, 10) 210 = 1024 Math.pow(2, -1) 2-1 = 0.5 Math.pow(9, 0.5) 90.5 = 3 Math.random generates a random number in the range [0…1) note: this function has no inputs; it returns a different number each call Math.random() Math.random() Math.random() .
93
Errors and Debugging in computer jargon, the term bug refers to an error in a program the process of systematically locating and fixing errors is debugging three types of errors can occur syntax errors: typographic errors e.g., omitting a quote or misspelling a function name since the browser catches these, they are usually "easy" to identify and fix run-time errors: occur when operations are applied to illegal values e.g., attempting to multiply a string or divide by zero also caught by the browser, which either produces an error message or else returns a special value (string multiplication produces NaN, for "Not a Number"; division by zero produces Infinity) logic errors: flaws in the design or implementation of a program whenever your program produces the wrong result since they are not caught by the browser (the program is legal, just not what you wanted), logic errors are hardest to identify useful technique for identifying bugs: diagnostic write statements at various intervals in the code, write out the values of key variables you can then isolate at what point the program is going wrong
94
Chapter 6 The History of Computers
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 6 The History of Computers
96
History of computing calculating devices have been around for millennia (e.g., abacus ~3,000 B.C.) modern "computing technology" traces its roots to the 16-17th centuries as part of the "Scientific Revolution", people like Kepler, Galileo, and Newton viewed the natural world as mechanistic and understandable this led to technological advances & innovation from simple mechanical calculating devices to powerful modern computers, computing technology has evolved through technological breakthroughs
97
Generation 0: Mechanical Computers
1642 – Pascal built a mechanical calculating machine used mechanical gears, a hand-crank, dials and knobs other similar machines followed 1805 – the first programmable device was Jacquard's loom the loom wove tapestries with elaborate, programmable patterns a pattern was represented by metal punch-cards, fed into the loom using the loom, it became possible to mass-produce tapestries, and even reprogram it to produce different patterns simply by changing the cards mid 1800's – Babbage designed his "analytical engine" its design expanded upon mechanical calculators, but was programmable via punch-cards (similar to Jacquard's loom) Babbage's vision described the general layout of modern computers he never completed a functional machine – his design was beyond the technology of the day
98
Generation 0 (cont.) 1890 – Hollerith invented tabulating machine
designed for tabulating 1890 U.S. Census data similar to Jacquard's loom and Babbage's analytical engine, it stored data on punch-cards, and could sort and tabulate using electrical pins using Hollerith's machine, census data was tabulated in 6 weeks (vs. 7 years for the 1880 census) Hollerith's company would become IBM 1930's – several engineers independently built "computers" using electromagnetic relays an electromagnetic relay is physical switch, which can be opened/closed via electrical current Zuse (Nazi Germany) – his machines were destroyed in WWII Atanasoff (Iowa State) – built a partially-working machine with his grad student Stibitz (Bell Labs) – built the MARK I computer that followed the designs of Babbage limited capabilities by modern standards: could store only 72 numbers, required 1/10 sec to add, 6 sec to multiply still, 100 times faster than previous technology
99
Generation 1: Vacuum Tubes
mid 1940's – vacuum tubes replaced relays a vacuum tube is a light bulb containing a partial vacuum to speed electron flow vacuum tubes could control the flow of electricity faster than relays since they had no moving parts invented by Lee de Forest in 1906 1940's – hybrid computers using vacuum tubes and relays were built COLOSSUS (1943) first "electronic computer", built by the British govt. (based on designs by Alan Turing) used to decode Nazi communications during the war the computer was top-secret, so did not influence other researchers ENIAC (1946) first publicly-acknowledged "electronic computer", built by Eckert & Mauchly (UPenn) contained 18,000 vacuum tubes and 1,500 relays weighed 30 tons, consumed 140 kwatts
100
Generation 1 (cont.) COLOSSUS and ENIAC were not general purpose computers could enter input using dials & knobs, paper tape but to perform a different computation, needed to reconfigure von Neumann popularized the idea of a "stored program" computer Memory stores both data and programs Central Processing Unit (CPU) executes by loading program instructions from memory and executing them in sequence Input/Output devices allow for interaction with the user virtually all modern machines follow this von Neumann Architecture (note: same basic design as Babbage) programming was still difficult and tedious each machine had its own machine language, 0's & 1's corresponding to the settings of physical components in 1950's, assembly languages replaced 0's & 1's with mnemonic names e.g., ADD instead of
101
Generation 2: Transistors
mid 1950's – transistors began to replace tubes a transistor is a piece of silicon whose conductivity can be turned on and off using an electric current they performed the same switching function of vacuum tubes, but were smaller, faster, more reliable, and cheaper to mass produce invented by Bardeen, Brattain, & Shockley in 1948 (earning them the 1956 Nobel Prize in physics) some historians claim the transistor was the most important invention of the 20th century computers became commercial as cost dropped high-level languages were designed to make programming more natural FORTRAN (1957, Backus at IBM) LISP (1959, McCarthy at MIT) BASIC (1959, Kemeny at Dartmouth) COBOL (1960, Murray-Hopper at DOD) the computer industry grew as businesses could afford to buy and use computers Eckert-Mauchly (1951), DEC (1957) IBM became market force in 1960's
102
Generation 3: Integrated Circuits
mid 1960's - integrated circuits (IC) were produced Noyce and Kilby independently developed techniques for packaging transistors and circuitry on a silicon chip (Kilby won the 2000 Nobel Prize in physics) this advance was made possible by miniaturization & improved manufacturing allowed for mass-producing useful circuitry 1971 – Intel marketed the first microprocessor, the 4004, a chip with all the circuitry for a calculator 1960's saw the rise of Operating Systems recall: an operating system is a collection of programs that manage peripheral devices and other resources in the 60's, operating systems enabled time-sharing, where users share a computer by swapping jobs in and out as computers became affordable to small businesses, specialized programming languages were developed Pascal (1971, Wirth), C (1972, Ritche)
103
(Intel Research. “Silicon—Moore’s Law.” October 2006.)
Generation 4: VLSI late 1970's - Very Large Scale Integration (VLSI) by the late 1970's, manufacturing advances allowed placing hundreds of thousands of transistors w/ circuitry on a chip this "very large scale integration" resulted in mass-produced microprocessors and other useful IC's since computers could be constructed by simply connecting powerful IC's and peripheral devices, they were easier to make and more affordable (Intel Research. “Silicon—Moore’s Law.” October 2006.)
104
Generation 4: VLSI (cont.)
with VLSI came the rise of personal computing Bill Gates & Paul Allen founded Microsoft Gates wrote a BASIC interpreter for the first PC (Altair) Steve Wozniak & Steve Jobs founded Apple went from Jobs' garage to $120 million in sales by 1980 IBM introduced PC Microsoft licensed the DOS operating system to IBM Apple countered with Macintosh introduced the modern GUI-based OS (which was mostly developed at Xerox) Microsoft countered with Windows Richest People in the World (Forbes.com, 3/8/07) 1. Bill Gates $56 billion 2. Warren Buffet $52 billion 3. Carlos Slim Helu $49 billion 4. Ingvar Kamprad $33 billion 5. Lakshmi Mittal $32 billion . 19. Paul Allen $18 billion 1980's - object-oriented programming began represented a new approach to program design which views a program as a collection of interacting software objects that model real-world entities Smalltalk (Kay, 1980), C++ (Stroustrup, 1985), Java (Sun, 1995)
105
Generation 5: Parallelism/Networks
the latest generation of computers is still hotly debated no new switching technologies, but changes in usage have occurred high-end machines (e.g. Web servers) can have multiple CPU's in 1997, highly parallel Deep Blue beat Kasparov in a chess match in 2003, successor Deep Junior played Kasparov to a draw most computers today are networked the Internet traces its roots to the 1969 ARPANet mainly used by government & universities until the late 80s/early 90s the Web was invented by Tim Berners-Lee in 1989 designed to allow physics researchers to share data and documents not popular until 1993 when Marc Andreessen developed a graphical browser (Mosaic) Andreessen would go on to found Netscape, and Internet Explorer soon followed (“Internet Domain Survey.” Internet Software Consortium, July 2006. “Netcraft Web Server Survey.” Netcraft, July 2006.)
106
Chapter 7 Event-Driven Pages
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 7 Event-Driven Pages
108
Event-driven Pages one popular feature of the Web is its interactive nature e.g., you click on buttons to make windows appear e.g., you enter credit card information in a form and submit it pages that respond to user actions such as mouse clicks or form entries are known as event-driven pages JavaScript code can be combined with HTML elements such as buttons, text fields, and text areas to produce event-driven pages an event handler is an HTML element that can be programmed to respond to a user’s actions the simplest event handler is a button a button can be associated with JavaScript code that will execute when the button is clicked
109
Buttons and Forms general form of a button element: for example,
<input type="button" value="BUTTON_LABEL" onclick="JAVASCRIPT_CODE" /> the TYPE attribute of the INPUT element identifies the element to be a button the VALUE attribute specifies the text label that appears on the button the ONCLICK attribute specifies the action to take place any JavaScript statement(s) can be assigned to the ONCLICK attribute this can be (and frequently is) a call to a JavaScript function for example, <input type="button" value="Click for Free Money" onclick="alert('Yeah, right.');" /> the predefined alert function displays a message in a new window here, the message 'Yeah, right.' is displayed at the click of the button a string can be denoted using either double("…") or single ('…') quotes here, single quotes must be used to avoid confusion with the ONCLICK quotes
110
Random Number Example recall the task of generating random numbers
earlier, we did this by embedding JavaScript code in SCRIPT tags each time the page was loaded in the browser, the code was executed and the random number was written into the HTML text using document.write DRAWBACK: the user had to reload for each random number ALTERNATIVE: place a button in the page with associated code for generating and displaying the random number each time the user clicks the button, the code for generating and displaying the number is executed
111
LuckyForm Example when the button is clicked, two JavaScript statements are executed a number in the range is randomly selected that number is displayed in an alert window
112
Output via Text Boxes a button provides a simple mechanism for user interaction in a Web page by clicking the button, the user initiates some action a text box is an event-handler that can display text (a word or phrase) unlike an alert window, the text box appears as a box embedded in the page text can be written to the box by JavaScript code (i.e., the box displays output) for example, we could reimplement the lucky number page using a text box the text box containing the random number is embedded in the page doesn't require the user to close the alert window after each number
113
Output via Text Boxes general form of a text box element:
<input type="text" id="BOX_NAME" size="NUM_CHARS" value="INITIAL_TEXT" /> the TYPE attribute of the INPUT element identifies the element to be a text box the ID attribute gives the element an identifier so that it can be referenced the SIZE attribute specifies the size of the box (number of characters that fit) the VALUE attribute specifies text that initially appears in the box to display text in a text box, a JavaScript assignment is used to assign to its value attribute as part of the assignment, must specify the absolute name of the box the general form is: document.getElementById('BOX_NAME').value = VALUE_TO_BE_DISPLAYED;
114
Text Box for Displaying Output
when the button is clicked, the function call DisplayNumber(); is executed the function generates the random number and assigns it to the text box as a result, each button click yields a new number in the box
115
Input via Text Boxes the user can enter text directly into the box
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('BOX_NAME').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 "93" similar to prompt, you must use parseFloat to convert the string to its numeric value example: we can revisit our temperature conversion page the user enters the Fahrenheit temperature in a text box at the click of a button, the input is accessed and converted to Celsius another text box is used to display the converted temperature
116
Text Boxes for Input fahrBox is used for input
the button's ONCLICK attribute specifies the code for converting the temperature celsiusBox is used for output
117
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 can write a simple page in which the user can enter a number, then double it by clicking a button
118
Text Areas a text area is similar to a text box but it can contain any number of text lines general form of a text area element: <textarea name="TEXTAREA_NAME" rows=NUM_ROWS cols=NUM_COLS wrap="virtual"> INITIAL_TEXT </textarea> the NAME 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 unlike a text box, opening and closing tags are used to define a text area any text appearing between the tags will be the initial text in the text area otherwise, the contents of a text area are accessed/assigned in the same way
119
Input/Output via Text Areas
the user enters first and last names into text boxes a long greeting is constructed using the names and assigned to the text area
120
Dynamic Images just as you can use user-initiated events to change the contents of text areas and text boxes, you can also dynamically modify images <img id="faceImg" src="happy.gif" alt="Happy Face" /> causes the image stored in the file happy.gif to appear in the page you can change the image by reassigning its SRC attribute similar to the way that text boxes/areas have their VALUE attribute reassigned document.getElementById('faceImg').src = "sad.gif"; replaces happy.gif with sad.gif
121
Dynamic Image Example initially the image is set to happy.gif
when a button is clicked, images is assigned a new SRC file
122
Simplifying buttons consider the button from greetbox.html:
the size of ONCLICK attribute makes the button complex and difficult to read plus, must be careful with nested quotes ("…" vs. '…') functions provide a mechanism for simplifying complex buttons such as this recall from Chapter 5: functions minimize the amount of detail that has to be considered e.g., can use Math.sqrt without worrying about how it works functions reduce the length and complexity of code e.g., a single call to Math.sqrt replaces the underlying complex algorithm
123
Simple user-defined functions
in addition to JavaScript's predefined functions, the user can define new functions in the HEAD section and call them within the page we will explore user-defined functions fully in Chapter 9 for now, the following simple form suffices for simplifying buttons a function definition begins with the word function followed by its name and () a function name should be descriptive of the task being performed lines beginning with // are comments that describe the function's behavior comments are ignored by the interpreter, but make code more user-readable the statements to be executed when the function is called are placed between the curly braces
124
Greeting revisited the code from the button is moved to the user-defined Greet function as a result, the button is greatly simplified GENERAL RULE: if more than one statement is to be associated with a button, define a separate function
125
Chapter 8 Algorithms and Programming Languages
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 8 Algorithms and Programming Languages
127
Algorithms the central concept underlying all computation is that of the algorithm an algorithm is a step-by-step sequence of instructions for carrying out some task 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 example: programming in JavaScript we have written programs that instruct the browser to carry out a particular task given the proper instructions, the browser is able to understand and produce the desired results
128
Algorithms in the Real World
the use of algorithms is not limited to the domain of computing e.g., recipes for baking cookies e.g., directions to your house there are many unfamiliar tasks in life that we could not complete without the aid of instructions in order for an algorithm to be effective, it must be stated in a manner that its intended executor can understand a recipe written for a master chef will look different than a recipe written for a college student as you have already experienced, computers are more demanding with regard to algorithm specifics than any human could be
129
Designing & Analyzing Algorithms
4 steps to solving problems (George Polya) understand the problem devise a plan carry out your plan examine the solution EXAMPLE: finding the oldest person in a room full of people understanding the problem initial condition – room full of people goal – identify the oldest person assumptions a person will give their real birthday 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 we will consider 2 different designs for solving this problem
130
Algorithm 1 Finding the oldest person (algorithm 1)
line up all the people along one wall ask the first person to state his or her name and birthday, then write this information down on a piece of paper for each successive person in line: ask the person for his or her name and birthday if the stated birthday is earlier than the birthday on the paper, cross out old information and write down the name and birthday of this person when you reach the end of the line, the name and birthday of the oldest person will be written on the paper
131
Algorithm 2 Finding the oldest person (algorithm 2)
line up all the people along one wall as long as there is more than one person in the line, repeatedly have the people pair up (1st with 2nd, 3rd with 4th, etc) – if there is an odd number of people, the last person will be without a partner ask each pair of people to compare their birthdays request that the younger of the two leave the line when there is only one person left in line, that person is the oldest
132
Algorithm Analysis determining which algorithm is "better" is not always clear cut it depends upon what features are most important to you if you want to be sure it works, choose the clearer algorithm if you care about the time or effort required, need to analyze performance algorithm 1 involves asking each person’s birthday and then comparing it to the birthday written on the page the amount of time to find the oldest person is proportional to the number of people if you double the amount of people, the time needed to find the oldest person will also double algorithm 2 allows you to perform multiple comparisons simultaneously the time needed to find the oldest person is proportional to the number of rounds it takes to shrink the line down to one person which turns out to be the logarithm (base 2) of the number of people if you double the amount of people, the time needed to find the oldest person increases by the cost of one more comparison the words algorithm and logarithm are similar – do not be confused by this algorithm: a step-by-step sequence of instructions for carrying out a task logarithm: the exponent to which a base is raised to produce a number e.g., 210 = 1024, so log2(1024) = 10
133
Algorithm Analysis (cont.)
when the problem size is large, performance differences can be dramatic for example, assume it takes 5 seconds to compare birthdays for algorithm 1: 100 people 5*100 = 500 seconds 200 people 5*200 = 1000 seconds 400 people 5*400 = 2000 seconds . . . 1,000,000 people 5*1,000,000 = 5,000,000 seconds for algorithm 2: 100 people 5* log2 100 = 35 seconds 200 people 5* log2 200 = 40 seconds 400 people 5* log2 400 = 45 seconds 1,000,000 people 5* log2 1,000,000 = 100 seconds
134
Big-Oh Notation to represent an algorithm’s performance in relation to the size of the problem, computer scientists use what is known as Big-Oh notation executing an O(N) algorithm requires time proportional to the size of problem given an O(N) algorithm, doubling the problem size doubles the work executing an O(log N) algorithm requires time proportional to the logarithm of the problem size given an O(log N) algorithm, doubling the problem size adds a constant amount of work based on our previous analysis: algorithm 1 is classified as O(N) algorithm 2 is O(log N)
135
Another Algorithm Example
SEARCHING: a common problem in computer science involves storing and maintaining large amounts of data, and then searching the data for particular values data storage and retrieval are key to many industry applications search algorithms are necessary to storing and retrieving data efficiently e.g., consider searching a large payroll database for a particular record if the computer selected entries at random, there is no assurance that the particular record will be found even if the record is found, it is likely to take a large amount of time a systematic approach assures that a given record will be found, and that it will be found more efficiently 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
136
Sequential Search sequential search is an algorithm that involves examining each list item in sequential order until the desired item is found sequential search for finding an item in a list start at the beginning of the list for each item in the list examine the item - if that item is the one you are seeking, then you are done if it is not the item you are seeking, then go on to the next item in the list if you reach the end of the list and have not found the item, then it was not in the list sequential search guarantees that you will find the item if it is in the list but it is not very practical for very large databases worst case: you may have to look at every entry in the list
137
Binary Search binary search involves continually cutting the desired search list in half until the item is found the algorithm is only applicable if the list is ordered e.g., a list of numbers in increasing order e.g., 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 value very quickly
138
Binary Search Example suppose you have a sorted list of state names, and want to find Illinois start by examining the middle entry (Missouri) since Missouri comes after Illinois alphabetically, can eliminate it and all entries that appear to the right 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 next, examine the middle of the remaining entries (Illinois) the desired entry is found
139
Search Analysis sequential search binary 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 sequential search is an O(N) 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 inspect/compare an entry, you rule out roughly half the remaining entries the amount of work required is proportional to the logarithm of the list size binary search is an O(log N) algorithm imagine searching a phone book of the United States (300 million people) sequential search requires at most 300 million inspections/comparisons binary search requires at most log2(300,000,000) = 29 inspections/comparisons
140
Another Algorithm Example
Newton’s Algorithm for finding the square root of N start with an initial approximation of 1 as long as the approximation isn’t close enough, repeatedly refine the approximation using the formula: newApproximation = (oldApproximation + N/oldApproximation)/2 example: finding the square root of 1024 algorithm analysis: Newton's Algorithm does converge on the square root because each successive approximation is closer than the previous one however, since the square root might be a non-terminating fraction it is difficult to define the exact number of steps for convergence in general, the difference between the given approximation and the actual square root is roughly cut in half by each successive refinement demonstrates O(log N) behavior
141
Algorithms and Programming
programming is all about designing and coding algorithms for solving problems the intended executor is the computer or a program executing on that computer instructions are written in programming languages which are more constrained and exact than human languages 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 executed
142
Machine Languages the first programming languages were known as machine languages a machine language consists of instructions that correspond directly to the hardware operations of a particular machine i.e., instructions deal directly with the computer’s physical components including main memory, registers, memory cells in 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 excerpt from a machine language program:
143
High-Level Languages in the early 1950’s, assembly languages evolved 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 correspond to hardware operations) in the late 1950's, high-level languages were introduced high-level 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 two high level languages that perform the same task (in JavaScript and C++)
144
Program Translation using a high-level language, the programmer is able to reason at a high-level of abstraction but programs must still be translated into machine language that the computer hardware can understand/execute there are two standard approaches to program translation interpretation compilation real-world analogy: translating a speech from one language to another an interpreter can be used provide a real-time translation the interpreter hears a phrase, translates, and immediately speaks the translation ADVANTAGE: the translation is immediate DISADVANTAGE: if you want to hear the speech again, must interpret all over again 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
145
Speech Translation Interpreter: Translator (compiler):
146
Interpreters for program translation, the interpretation approach relies on a program known as an interpreter to translate and execute high-level statements the interpreter reads one high-level statement at a time, immediately translating and executing the statement before processing the next one JavaScript is an interpreted language
147
Compilers the compilation approach relies on a program known as a compiler to translate the entire high-level language program into its equivalent machine-language instructions the resulting machine-language program can be executed directly on the computer most languages used for the development of commercial software employ the compilation technique (C, C++)
148
Interpreters and Compilers
tradeoffs between interpretation and compilation interpreter produces results almost immediately particularly useful for dynamic, interactive features of web pages program executes more slowly (slight delay between the execution of statements) compiler produces machine-language program that can run directly on the 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
149
Chapter 9 Abstraction and User-Defined Functions
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 9 Abstraction and User-Defined Functions
151
Abstraction abstraction is the process of ignoring minutiae and focusing on the big picture in modern life, we are constantly confronted with complexity we don't necessarily know how it works, but we know how to use it e.g., how does a TV work? a car? a computer? we survive in the face of complexity by abstracting away details to use a TV/car/computer, it's not important to understand the inner workings we ignore unimportant details and focus on those features relevant to using it e.g., TV has power switch, volume control, channel changer, … JavaScript functions (like Math.sqrt) provide computational abstraction a function encapsulates some computation & hides the details from the user the user only needs to know how to call the function, not how it works Chapter 7 introduced simple user-defined functions could encapsulate the statements associated with a button, call the function as needed
152
General Function Form to write general-purpose functions, we can extend definitions to include: 1) parameters, 2) local variables, and 3) return statements parameters are variables that correspond to the function’s inputs (if any) parameters appear in the parentheses, separated by commas local variables are 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 conflicts with other functions a return statement is a statement that specifies an output value consists of the keyword return followed by a variable or expression
153
Functions with Inputs most of the predefined function we have considered expect at least on input e.g., Math.sqrt takes a number as input, and returns its square root as output Math.sqrt(9) 3 e.g., Math.max takes two numbers as inputs, and returns the maximum as output Math.max(7, 3) 7 in English, the word parameter refers to some aspect of a system that can be varied in order to control its behavior in JavaScript, a parameter is a variable (declared inside the function's parentheses) whose value is automatically initialized to the corresponding input value when the function is called parameters allow the same function to perform different (but related) tasks when called with different input values the call ChangeImage("happy.gif") will assign the input "happy.gif" to the parameter imgSource, resulting in the image being assigned to that file __________________________________________________ the call ChangeImage("sad.gif") will assign the input "sad.gif" to the parameter imgSource, resulting in the image being assigned to that file
154
Newpics Page in newpics.html, each button performs a similar task - changing the image file the single ChangeImage function suffices for each (using different inputs)
155
Newmac Page similarly, we could redefine oldmac.html from Chapter 5
OldMacVerse has 2 inputs: the animal and sound for that verse this function can be used to display any verse, given the animal and sound
156
Multiple Inputs if a function has more than one input,
parameters in the function definition are separated by commas input values in the function call are separated by commas values are matched to parameters by order 1st input value in the function call is assigned to the 1st parameter in the function 2nd input value in the function call is assigned to the 2nd parameter in the function . . . function OldMacVerse(animal, sound) // Assumes: animal and sound are strings // Results: displays corresponding Old MacDonald verse { . . . } OldMacVerse("cow", "moo"); OldMacVerse("moo", "cow");
157
Parameters and Locals parameters play an important role in functions
they facilitate the creation of generalized computations i.e., 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 variable, meaning it exists only inside its particular function when the function is called, memory cells are allocated for the parameters and each input from the call is assigned to its corresponding parameter once a parameter has been assigned a value, you can refer to that parameter within the function just as you would any other variable when the function terminates, the parameters “go away,” and their associated memory cells are freed by default, variables other than parameters are considered global, meaning they exist and can be accessed by JavaScript code anywhere in the page note: 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 accessible outside that function, the global variable is accessible
158
Local vs. Global here, the variable names animal and sound are used for parameters in the function definition (local variables) used for variables in the BODY (global variables) we can think of these as completely separate variables, identifiable via a subscript animalOldMacVerse and soundOldMacVerse are used in the function animalBODY and soundBODY are used in the BODY
159
Declaring Local Variables
we have seen that variables are useful for storing intermediate steps in a complex computation within a user-defined function, the programmer is free to create new variables and use them in specifying the function’s computation however, by default, new variables used in a function are global but what if the same variable name is already used elsewhere? to avoid name conflicts, the programmer should declare temporary variables to be local a variable declaration is a statement that lists all local variables to be used in a function (usually the first statement in a function) general form: var LOCAL_1, LOCAL_2, . . ., LOCAL_n; function IncomeTax(income, itemized) // Assumes: income >= 0, itemized >= 0 // Results: displays flat tax (13%) due after deductions { var deduction, taxableIncome, totalTax; deduction = Math.max(itemized, 4150); taxableIncome = Math.max(income - deduction, 0); totalTax = 0.13*taxableIncome alert("You owe $" + totalTax); } since these variables are declared as local, they will not affect (or be affected by) any variables with the same names elsewhere in the page
160
Functions with Return displaying results using document.write or alert is OK for some functions for full generality, we need to be able to return an output value, which can then be used in other computations e.g., number = Math.sqrt(9); amountOwed = IncomeTax(38000, 6500); a return statement can be added to a function to specify its output value when the return statement is reached, the variable or expression is evaluated and its value is returned as the function's output general form: return OUTPUT_VALUE; function IncomeTax(income, itemized) // Assumes: income >= 0, itemized >= 0 // Returns: flat tax (13%) due after deductions { var deduction, taxableIncome, totalTax; deduction = Math.max(itemized, 4150); taxableIncome = Math.max(income - deduction, 0); totalTax = 0.13*taxableIncome return totalTax; } since this function returns the value, it can be used in other computations, e.g., calculate amount owed in 4 payments: payment = IncomeTax(38000, 6500)/4;
161
Newconvert Page if the same computation must be done repeatedly, a function can greatly simplify the page here, FahrToCelsius is called twice to convert two different temperatures
162
Designing Functions functions do not add any computational power to the language a function definition simply encapsulates other statements still, the capacity to define and use functions is key to solving complex problems, as well as to developing reusable code encapsulating repetitive tasks can shorten and simplify code functions provide units of computational abstraction – user can ignore details functions are self-contained, so can easily be reused in different applications when is it worthwhile to define a function? if a particular computation is complex—meaning that it requires extra variables and/or multiple lines to define if you have to perform a particular computation repeatedly within a page when defining a function, you must identify the inputs the computation to be performed using those inputs the output
163
Design Example consider the task of designing an online Magic 8-ball (Mattell, Inc.) must be able to ask a yes/no type question receive an answer (presumably, at random) could use: a text area for entering the question (which could be several lines long) a text box for displaying the answer (which should be short) a button for initiating the action – which involves calling a function to process the question, select an answer, and display it in the text box
164
random.js general-purpose functions can be grouped together in a library a library is a text file that contains one or more function definitions once the functions are defined in the library, that library can be loaded into pages as needed e.g., the random.js library contains useful functions for generating random values to load a library of functions in a page, use a special pair of SCRIPT tags <script type="text/javascript" src="URL_OR_LOCAL_FILENAME"> </script>
165
Using random.js in the page below, the random.js library is accessed via the Web you can download the file and store it on your own machine 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) note: the RandomOneOf function from random.js would similarly be useful for the Magic 8-ball page (in selecting possible answers at random)
166
Errors to Avoid When beginning programmers attempt to load a JavaScript code library, errors of two types commonly occur: if the SCRIPT tags are malformed or the name/address of the library is incorrect, the library will fail to load this will not cause an error in itself, but any subsequent attempt to call a function from the library will produce “Error: Object Expected” (using Internet Explorer) or “Error: XXX is not a function” (using Firefox), where XXX is the entered name when you use the SRC attribute in a pair of SCRIPT tags to load a code library, you cannot place additional JavaScript code between the tags think of the SRC attribute as causing the contents of the library to be inserted between the tags, overwriting any other code that was erroneously placed there <script type="text/javascript" src="FILENAME"> ANYTHING PLACED IN HERE WILL BE IGNORED </script> if you want additional JavaScript code or another library, you must use another pair of SCRIPT tags
167
Chapter 10 Computer Science as a Discipline
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 10 Computer Science as a Discipline
169
Computer “Science” some people argue that computer science is not a science in the same sense that biology and chemistry are the interdisciplinary nature of computer science has made it hard to classify computer science is the study of computation (more than just machinery) it involves all aspects of problem solving, including the design and analysis of algorithms the formalization of algorithms as programs the development of computational devices for executing programs the theoretical study of the power and limitations of computing whether this constitutes a "science" is a matter of interpretation certainly, computer science represents a rigorous approach to understanding complex phenomena and problem solving
170
Scientific Method the process developed by the scientific community for examining observations and events is known as the scientific method many activities carried out by computer scientists follow the scientific method e.g., designing and implementing a large database system requires hypothesizing about its behavior under various conditioning, experimenting to test those hypotheses, analyzing the results, and possibly redesigning e.g., debugging a complex program requires forming hypotheses about where an error might be occurring, experimenting to test those hypotheses, analyzing the results, and fixing the bugs
171
Artificial Science the distinction between computer science and natural sciences like biology, chemistry, and physics is the type of systems being studied natural sciences study naturally occurring phenomena and attempt to extract underlying laws of nature computer science study human-made constructs: programs, computers, and computational modes Herbert Simon coined the phrase "artificial science" to distinguish computer science from the natural sciences in Europe, computer science is commonly called "Informatics" emphasizes the role of information processing as opposed to machinery the term "Algorithmics" has also been proposed emphasizes the role of algorithms and problem solving other related fields study computation from different perspectives computer engineering focuses on the design and construction of computers information systems management focuses on business applications
172
Computer Science Themes
since computation encompasses many different types of activities, computer science research is often difficult to classify three recurring themes define the discipline
173
Hardware hardware refers to the physical components of a computer and its supporting devices most modern computers implement the von Neumann architecture CPU + memory + input/output devices ongoing research seeks to improve hardware design and organization circuit designers create smaller, faster, more energy-efficient chips microchip manufacturers seek to miniaturize and streamline production systems architects research methods to increase throughput (the amount of work done in a given time period) e.g., parallel processing – splitting the computation across multiple CPUs e.g., networking – connecting computers to share information and work
174
Software software refers to the programs that execute on computers
3 basic software categories systems software: programs that directly control the execution of hardware components (e.g., operating systems) development software: programs that are used as tools in the development of other programs (e.g. Microsoft.NET, Java SDK) applications software: all other programs, which perform a wide variety of tasks (e.g., web browsers, word processors, games) many careers in computer science are related to the design, development, testing, and maintenance of software language designers develop and extend programming languages for easier and more efficient solutions programmers design and code algorithms for execution on a computer systems analysts analyze program designs and manage development
175
Theory theoretical computer scientists strive to understand the capabilities of algorithms and computers (deeply rooted in math and formal logic) example: the Turing machine is an abstract computational machine invented by computer pioneer Alan Turing consists of: a potentially infinite tape on which characters can be written a processing unit that can read and write on the tape, move in either direction, and distinguish between a finite number of states significance of the Turing machine it is programmable (example below is programmed to distinguish between an even or odd number of a's on the tape) provably as powerful as any modern computer, but simpler so provides a manageable tool for studying computation Turing used this simpler model to prove there are problems that cannot be solved by any computer!
176
Subfields of Computer Science
computer science can be divided into subfields each subfield takes a unique approach to computation however the common themes of computer science (hardware, software, and theory) influence every subfield (Denning, Peter. “Computer Science: The Discipline.” In Encyclopedia of Computer Science, 4th ed., 2000.)
177
Algorithms and Data Structures
subfield that involves developing, analyzing, and implementing algorithms for solving problems application: encryption encryption is the process of encoding a message so that it is decipherable only by its intended recipient Caesar cipher: shift each letter three down in the alphabet e.g., ET TU BRUTE HW WX EUXWH Caesar cipher is an example of private-key encryption relies on the sender and the recipient sharing a secret key some modern encryption algorithms rely on private keys e.g., Digital Encryption Standard (DES) utilizes 56-bit keys
178
Public-Key Encryption
private-key encryption assumes that the sender and the recipient have agreed upon some key ahead of time (which introduces other security risks) Whitfield Diffie and Martin Hellman proposed public-key encryption assign each party a pair of associated keys, one is public and the other is private a message encoded with a public key requires the corresponding private key for decoding, and vice versa almost all secure communications on the Internet use public key encryption allows for double encryption to also verify the identity of the sender you can encode messages with your own private key and the recipient’s public key, and decode the message in reverse
179
Architecture subfield concerned with methods of organizing hardware components into efficient, reliable systems application: parallel processing multiple processors can sometimes be utilized to share the computational load there are costs associated with coordinating the processors and dividing the work, so not well suited for all tasks understanding when parallel processing can be used effectively is a common task for computer architects e.g., Core 2 Duo processor integrates the circuitry for 2 processors can execute two different instructions simultaneously, potentially double execution speed e.g., high-end Web Servers utilize multiple processors can service multiple requests simultaneously by distributing the load among the processors Deep Blue, IBM's chess playing computer, contained 32 general purpose processors and 512 special-purpose chess processors the processors worked in parallel to evaluate chess moves (could generate and evaluate 200 million chess moves per second) in 1997, Deep Blue became the first computer to beat a world champion in a chess tournament
180
Operating Systems and Networks
subfield concerned with mechanisms to control the hardware and software components of computer systems application: operating systems mediate between hardware and software time-sharing - allowed for multiple users to work on the same computer each user is allocated a portion of the processor, and the processor rotates among tasks so rapidly that it appears to be executing tasks simultaneously multitasking – a single user can run multiple programs simultaneously each application is allocated a portion of the memory application: networks allow computers to communicate and share resources wide area network (WAN) – connects computers over long distances (e.g., Internet) local area network (LAN) – connects computers over short distances (e.g., same room or building) Ethernet is a family of technologies for building LANs simplest form uses broadcasting approach
181
Software Engineering subfield concerned with creating effective software systems large projects can encompass millions of lines of code teams of programmers work together to make an integrated whole coordination and testing are key to successful projects software demand continues to grow, placing pressure on programmers to produce at faster rates clearly, there is a limit to personal productivity simply adding more programmers does not solve the problem: increasing numbers means increased complexity, and coordination becomes an even bigger challenge in recent years, the adoption of the object-oriented programming methodology has made it easier to reuse code
182
Artificial Intelligence
subfield that attempts to make computers exhibit human-like characteristics (e.g., the ability to reason and think) in 1950, Turing predicted intelligent computers by 2000 (still not even close) but, progress has been made in many A.I. realms robots in manufacturing expert systems – programs that encapsulate expert knowledge in a specific domain (e.g., for medical diagnosis) neural computing – design of architectures that mimic the brain
183
Bioinformatics subfield that bridges the gap between biology and computer science focuses on using computers and computer science techniques to solve biological problems computers are integrated with various scientific tools e.g., microscopes connected to computers and digital cameras computer are used to model biological systems e.g., pharmaceutical companies model drug interactions to save time and money computers are used to store and process large amounts of biological data e.g., Human Genome Project stores and provides tools for studying DNA
184
The Ethics of Computing
as technology becomes more prevalent in society, computing professionals must ensure that hardware and software are used safely, fairly, and effectively
185
Chapter 11 Conditional Execution
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 11 Conditional Execution
187
Conditional Execution
so far, all of the code you have written has been unconditionally executed the browser carried out statements in the same set order in contrast, many programming tasks require code that reacts differently under varying circumstances or conditions e.g., a student's course grade depends upon his/her average e.g., an ESP test requires recognizing when a subject guessed right e.g., the outcome of a game depends upon die rolls or player moves conditional execution refers to a program’s ability to execute a statement or sequence of statements only if some condition holds true
188
If Statements in JavaScript, the simplest form of conditional statement is the if statement one action is taken if some condition is true, but a different action is taken if the condition is not true (called the else case) the else case is optional general form of the if statement:
189
Braces in If Statements
some people prefer braces on separate lines formatted like this: if (BOOLEAN_TEST) { STATEMENTS_EXECUTED_IF_TRUE } else STATEMENTS_EXECUTED_IF_FALSE either style is acceptable, but be consistent! properly aligning the code (with if-else lining up and statements indented) is central in producing code that is easy to read and modify technically, you can omit the braces if there is only one statement however, THIS IS STRONGLY DISCOURAGED! can lead to tricky errors if the code is ever modified
190
Boolean Tests the test that controls an if statement can be any boolean expression (i.e., an expression that evaluates to either true or false) boolean tests are formed using relational operators because they test the relationships between values NOTE: == is for comparisons = is for assignments the boolean test in an if statement determines the code that will be executed if the test is true, then the code inside the subsequent curly braces will execute if the test is false, then the code inside the curly braces following the else will execute note that if the test is false and there is no else case, the program moves on to the statement directly after the if
191
If Statement Examples an if statement is known as a control statement, since its purpose is to control the execution of other statements
192
Example within a Page
193
Accessing Text Fields recall that values entered via text boxes/areas are always returned as strings if (document.getElementById('age').value >= 18) { alert("You are old enough to vote."); } else { alert("Sorry. You are too young to vote."); will say that a 2-year old can vote, but a 102-year old can't! WHY? if you wish to treat a value obtained from a text box or text area as a number, you must use the parseFloat function to convert it age = parseFloat(document.getElementById('age').value); if (age >= 18) { alert("You are old enough to vote."); } else { alert("Sorry. You are too young to vote."); will behave as expected
194
Nested If Statements programming tasks often require code that responds to more than one condition this can be accomplished by nesting one if statement inside of another example: determining wind-chill wind-chill is only defined for temperatures less than or equal to 50 degrees the initial if test is to determine if it is a valid temperature to calculate wind-chill the nested if statement only executes if the outer test is true
195
Cascading If-else Statements
nested if-else structures are known as cascading if-else statements because control cascades down the branches the topmost level is evaluated first if the test succeeds, then the corresponding statements are executed and control moves to the next statement following the cascading if if the 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 example: nested if-else structure
196
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 read/understand example: nested if statements vs. a more readable else-if
197
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
198
Die Roll Page the RandomInt function from random.js is used to select the random roll depending on the roll value, the correct image is displayed since more than two possibilities, a cascading if-else is needed
199
Generalizing Code note that each case in the cascading if-else follows the same pattern if (roll == 1) { document.getElementById('die').src = " } else if (roll == 2) { document.getElementById('die').src = " else if (roll == 3) { document.getElementById('die').src = " else if (roll == 4) { document.getElementById('die').src = " else if (roll == 5) { document.getElementById('die').src = " else { document.getElementById('die').src = " this entire cascading if-else structure could be replaced by the following: document.getElementById('die').src = " + roll + ".gif";
200
Counters in software applications, if statements are often used to count occurrences of conditional or user-initiated events e.g., count the number of times dice rolls come up doubles e.g., count the number of times the user guesses a number correctly any variable that is used to record occurrences of an event is known as a counter initially, the counter is set to zero each time the specified action occurs, the counter is incremented after a given time period, the value stored in the counter will tell you the number of times the desired event took place
201
Logical Connectives sometimes, simple comparisons between two values may not be adequate to express the conditions under which code should execute JavaScript provides operators for expressing multipart tests logical AND (&&): represents the conjunction of two things (TEST1 && TEST2) is true if both TEST1 and TEST2 are true if (roll1 == 4 && roll2 == 4) { // code to be executed when double fours are rolled } logical OR (||): represents the disjunction of two things (TEST1 || TEST2) is true if either TEST1 or TEST2 are true if (roll1 == 4 || roll2 == 4) { // code to be executed when at least one four is rolled logical NOT (!): represents negation (!TEST1) is true only if TEST1 is false if (!(roll1 == 4 || roll2 == 4)) { // code to be executed when neither roll is a four
202
Chapter 12 Data Representation
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 12 Data Representation
204
Analog vs. Digital there are two ways data can be stored electronically analog signals represent data in a way that is analogous to real life signals can vary continuously across an infinite range of values e.g., frequencies on an old-fashioned radio with a dial digital signals utilize only a finite set of values e.g., frequencies on a modern radio with digital display the major tradeoff between analog and digital is variability vs. reproducibility analog allows for a (potentially) infinite number of unique signals, but they are harder to reproduce good for storing data that is highly variable but does not need to be reproduced exactly digital signals limit the number of representable signals, but they are easily remembered and reproduced good for storing data when reproducibility is paramount
205
Binary Numbers modern computers save and manipulate data as discrete (digital) values the most effective systems use two distinct binary states for data representation in essence, all data is stored as binary numbers in the binary number system, all values are represented using only the two binary digits 0 and 1, which are called bits binary representation converting binary to decimal
206
Decimal Binary algorithm for converting from decimal (D) to binary (B):
207
Representing Integers
when an integer value must be saved on a computer, its binary equivalent can be encoded as a bit pattern and stored digitally usually, a fixed size (e.g., 32 bits) is used for each integer so that the computer knows where one integer ends and another begins the initial bit in each pattern acts as the sign bit (0=positive, 1=negative) negative numbers are represented in two’s complement notation the "largest" bit pattern corresponds to the smallest absolute value (-1)
208
Representing Real Numbers
a real number can be uniquely identified by the two components of its scientific notation (fractional part and the exponent) = x = 42 x 10-6 thus, any real number can be stored as a pair of integers real numbers stored in this format are known as floating point numbers, since the decimal point moves (floats) to normalize the fraction standard formats exist for storing real numbers, using either 32 or 64bits most programming languages represent integers and reals differently JavaScript simplifies things by using IEEE double-precision floating point for all numbers
209
Representing Characters
characters have no natural correspondence to binary numbers computer scientists devised an arbitrary system for representing characters as bit patterns ASCII (American Standard Code for Information Interchange) maps each character to a specific 8-bit pattern note that all digits are contiguous, as are lower- and upper-case letters '0' < '1' < … < '9' 'A' < 'B' < … < 'Z' 'a' < 'b' < … < 'z' Unicode is a 16-bit extension to ASCII that supports other languages
210
Representing Text strings can be represented as sequences of ASCII codes, one for each character in the string specific programs may store additional information along with the ASCII codes e.g. programming languages will often store the number of characters along with the ASCII codes e.g., word processing programs will insert special character symbols to denote formatting (analogous to HTML tags in a Web page)
211
Representing Sounds computers are capable of representing much more than numbers and text complex data requires additional techniques and algorithms EXAMPLE: representing sounds sounds are inherently analog signals with a specific amplitudes and frequencies when sound waves reach your ear, they cause your eardrum to vibrate, and your brain interprets the vibration as sound e.g. telephones translate a waveform into electrical signals, which are then sent over a wire and converted back to sound e.g. phonographs interpret waveforms stored on on grooves of a disk (similar to audio cassettes) analog signals cannot be reproduced exactly, but this is not usually a problem since the human ear is unlikely to notice small inconsistencies
212
Representing Sounds (cont.)
when analog recordings are repeatedly duplicated, small errors that were originally unnoticed begin to propagate digital recordings can be reproduced exactly without any deterioration in sound quality analog waveforms must be converted to a sequence of discrete values digital sampling is the process in which the amplitude of a wave is measured at regular intervals, and stored as discrete measurements frequent measurements must be taken to ensure high quality (e.g., 44,100 readings per second for a CD) this results in massive amounts of storage techniques are used to compress the data and reduce file sizes (e.g., MP3, WAV)
213
Representing Images EXAMPLE: representing images
images are stored using a variety of formats and compression techniques the simplest representation is a bitmap bitmaps partition an image into a grid of picture elements, called pixels, and then convert each pixel into a bit pattern resolution refers to the sharpness or clarity of an image bitmaps that are divided into smaller pixels will yield higher resolution images the left image is stored using 96 pixels per square inch, and the right image is stored using 48 pixels per square inch the left image appears sharp, but has twice the storage requirements
214
Representing Images (cont.)
when creating a bitmap of a color image, more than one bit is required to represent each pixel the most common system is to translate each pixel into a 24 bit code, known as its RGB value: 8 bits to represent the intensity of each red/green/blue component common image formats implement various compression techniques to reduce storage size GIF (Graphics Interchange Format) a lossless format, meaning no information is lost in the compression commonly used for precise pictures, such as line drawings JPEG (Joint Photographic Experts Group) a lossy format, so the compression is not fully reversible (but more efficient) commonly used for photographs
215
Distinguishing Data Types
how does a computer know what type of value is stored in a particular piece of memory? short answer: it doesn't when a program stores data in memory, it must store additional information as to what type of data the bit pattern represents thus, the same bit pattern might represent different values in different contexts
216
Chapter 13 Conditional Repetition
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 13 Conditional Repetition
218
Conditional Repetition
an if statement is known as a control statement it is used to control the execution of other JavaScript statements provides for conditional execution is useful for solving problems that involve choices either do this or don't, based on some condition (if) either do this or do that, based on some condition (if-else) closely related to the concept of conditional execution is conditional repetition many problems involve repeating some task over and over until a specific condition is met e.g., rolling dice until a 7 is obtained e.g., repeatedly prompting the user for a valid input in JavaScript, while loops provide for conditional repetition
219
While Loops a while loop resembles an if statement in that its behavior is dependent on a boolean condition. however, the statements inside a while loop’s curly braces (a.k.a. the loop body) are executed repeatedly as long as the condition remains true general form: when the browser encounters a while loop, it first evaluates the boolean test if the test succeeds, then the statements inside the loop are executed in order, just like an if statement once all the statements have been executed, program control returns to the beginning of the loop the loop test is evaluated again, and if it succeeds, the loop body statements are executed again this process repeats until the boolean test fails
220
While Loop Example example: roll two dice repeatedly until doubles are obtained note: even though while loops and if statements look similar, they are very different control statements an if statement may execute its code 1 time or not at all a while loop may execute its code an arbitrary number of times (including not at all) sample output:
221
While Loop Page
222
Avoiding redundancy note the redundancy in the code
must perform the initial dice roll before the loop begins then, have to repeatedly re-roll inside the loop can avoid this by either: "priming the loop" with default values that allow the loop to execute defining a Boolean "flag" to determine when the loop should continue
223
Loop Tests note: the loop test defines the condition under which the loop continues this is often backwards from the way we think about loops e.g., read input until you get a positive number (i.e., until input > 0) while (input <= 0) { } e.g., keep rolling dice until you get doubles (i.e., until roll1 == roll2) while (roll1 != roll2) { } e.g., keep rolling dice until you get double fours (i.e., until roll1 == 4 && roll2 = 4) while (roll1 != 4 || roll2 != 4) { } DeMorgan's Law: !(X && Y) == (!X || !Y) !(X || Y) == (!X && !Y)
224
Counter-Driven Loops since a while loop is controlled by a condition, it is usually impossible to predict the number of repetitions that will occur e.g., how many dice rolls will it take to get doubles? a while loop can also be used to repeat a task some fixed number of times implemented by using a while loop whose test is based on a counter general form of counter-driven while loop: the counter is initially set to 0 before the loop begins, and is incremented at the end of the loop body the counter keeps track of how many times the statements in the loop body have executed when the number of repetitions reaches the desired number, the loop test fails and the loop terminates
225
Counter-Driven Loops examples:
226
Counter-Driven Loops Page
227
Infinite Loops the browser will repeatedly execute statements in the body of a while loop as long as the loop test succeeds (evaluates to true) it is possible that the test will always succeed and the loop will run forever a loop that runs forever is known as an infinite loop (or a black hole loop) to guard against infinite loops, make sure that some part of the loop test changes inside the loop in the above example, repCount is not updated in the loop so there is no chance of terminating once the loop starts an infinite loop may freeze up the browser sometimes, clicking the Stop button will suffice to interrupt the browser other times, you may need to restart the browser
228
Variables and Repetition
any variable can be employed to control the number of loop repetitions and the variable can be updated in various ways example: countdown
229
Countdown Page
230
Example: Hailstone Sequences
an interesting unsolved problem in mathematics: hailstone sequence start with any positive integer if the number is odd, then multiply the number by three and add one; otherwise, divide it by two repeat as many times as desired for example: 5, 16, 8, 4, 2, 1, 4, 2, 1, 4, 2, 1, … it is conjectured that, no matter what positive integer you start with, you will always end up in the loop this has been verified for all starting number up to 1,200,000,000,000 but, it still has not been proven to hold for ALL starting numbers we can define a JavaScript function for experimenting with this problem the hailstone function will generate the sequence given a starting number
231
Chapter 14 Inside the Computer - the von Neumann Architecture
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 14 Inside the Computer - the von Neumann Architecture
233
CPU Subunits and Datapath
recall the von Neumann architecture Central Processing Unit (CPU) Input/Output devices Memory the CPU acts as the brain of the computer it obtains data and instructions from memory it carries out instructions it stores results back to memory the program instructions that are executed by the CPU are in the machine language of that CPU users can write programs in a high-level language, but those high-level instructions must be translated into machine language before executing even programs that exhibit complex behavior are specified to the CPU as sequences of simple machine-language commands the CPU can execute these instructions at such a high speed that complex programmatic behavior is achieved
234
CPU Subunits the CPU is comprised of several subunits, each playing a specific role in processor functioning Arithmetic Logic Unit (ALU): circuitry that performs the actual operations on data (addition, subtraction, bit manipulations) Registers: memory locations built into the CPU (to provide fast access) the transfer of data between registers and main memory occurs across a collection of wires called a bus Control Unit (CU): circuitry in charge of fetching data and instructions from main memory, as well as controlling the flow of data between registers and the ALU
235
CPU Datapath Cycles the path that data follows within the CPU, traveling along buses from registers to the ALU and then back to registers, is known as the CPU datapath a single rotation around the CPU datapath is referred to as a CPU datapath cycle recall earlier that we defined CPU speed as measuring the number of instructions that a CPU can carry out per second CPU speed = the number of CPU cycles per second e.g., a 2.5GHz CPU can perform 2.5 billion cycles per second CPUs cannot be compared solely on the basis of their speeds since CPUs have different instruction sets, one CPU may be able to complete more complex tasks in a single cycle so, a slower CPU with a richer instruction set may complete some tasks faster
236
Datapath Simulator accompanying the text is a datapath simulator
a.k.a. the Knob & Switch Computer developed by Grant Braught at Dickinson College allows the user to enter data directly into the register boxes and configure the CPU hardware by clicking on knobs and switches by clicking on the knobs labeled A Bus Address and B Bus Address, the user can select which registers will be accessed here, registers R0 and R1 are selected by clicking on the knob labeled ALU Operation, the user can select which operation will be performed on the specified register data here, the addition operation (A+B) is selected by clicking on the knob labeled C Bus Address, the user can select which register the result will be written to here, register R2 is selected
237
Datapath Simulator (cont.)
when the user clicks on the Execute button, a CPU datapath cycle is executed with the given settings data can be observed as it moves around the datapath in the 1st step, data values are retrieved from the specified registers (R0 and R1) and passed along the A and B buses, respectively
238
Datapath Simulator (cont.)
data can be observed as it moves around the datapath in the 2nd step, the data values from the A and B buses are operated on by the ALU, with the result passed along the C bus
239
Datapath Simulator (cont.)
data can be observed as it moves around the datapath in the 3rd step, the data on the C bus is written to the specified register (R2) the end result of the datapath cycle is that the contents of two registers are added and the result is stored in a different register
240
CPU and Main Memory the CPU datapath describes the way in which a computer manipulates data stored in registers but, it does not explain how data gets into registers in the first place or, how the results of ALU operations are accessed outside the CPU both of these tasks involve connections between the CPU and main memory all active programs and data are stored in the main memory of a computer main memory is comprised of a large number of memory locations, with each location accessible via an address a bus connects main memory to the CPU, enabling the computer to copy data and instructions to registers, and then copy the results of computations back to main memory
241
Main Memory Data Transfer
as a program is executed, the control unit processes the program instructions and identifies which data values are needed to carry out the specified tasks the required values are then fetched from main memory along the main memory bus, loaded into registers, and used in ALU operations note: data must be copied from main memory into registers BEFORE it can be operated on in practice, the data transfer takes much longer than a single datapath cycle (due mainly to the distance that must be covered) modern CPUs compensate by fetching multiple instructions at once – ideally, the CPU will predict which instructions will be needed next and prefetch them
242
Data Transfer Example example: suppose you had a file containing 1,000 numbers and wanted to compute the sum of those numbers first, need to load the data from the file into main memory — for example, at memory locations 500 through 1499 then, the control unit would carry out the following steps to add the numbers and store the resulting sum back in main memory
243
Datapath w/ Memory Simulator
we can extend the datapath simulator to integrate main memory main memory is displayed as a series of boxes, labeled with addresses 0-31 a Main Memory Bus is added to transfer data to and from main memory buses have switches that open and close when the user clicks on them by selecting the radio button labeled R/W in the Main Memory partition, the user can select a memory address here, address 0 is selected by clicking on the Main Memory Bus and C Bus, they can be opened/closed here, the buses are configured to allow data to flow from main memory to the register the other components of the datapath are configured as before
244
Memory Simulator (cont.)
for example, suppose we wanted to add the contents of address 0 and address 1, and store the result in address 2 in the 1st step, copy the data from address 0 into a register, say R0 note: the A Bus, B Bus, and ALU settings are irrelevant since the C Bus is disconnected
245
Memory Simulator (cont.)
in the 2nd step, similarly copy the data from address 1 into a register, say R1 note: when the simulator executes, there is a noticeable (and intentional) delay as data moves on the Main Memory Bus
246
Memory Simulator (cont.)
in the 3rd step, the contents of R0 and R1 are added and the result is sent directly to address 2 in some CPUs, this would require 2 steps: send the result to a register, then copy the register to main memory
247
Stored-Program Computer
the last component of the CPU is a fully functioning, automatic control unit recall that in the simulations, tasks were defined by selecting registers and ALU operations via knobs, switches, and buses the idea behind a stored-program computer is that tasks can be represented as instructions stored in main memory along with data the control unit must fetch, decode, and execute those instructions recall: each type of CPU has its own machine language for representing instructions for example, we could define an instruction for our simulator by specifying the knob and switch settings for the datapath since real world CPUs contain an extremely large number of physical components, a more compact representation is required machine language instructions are represented as binary strings, where the bits correspond to hardware settings
248
Simulator Machine Language
1st two instructions – select ALU operation and registers to operate on next 3 instructions – control flow of data between main memory and datapath last instruction – mark the end of instruction sequence
249
Control Unit the control unit fetches each machine language instruction from memory, interprets its meaning, carries out the specified CPU cycle, and then moves on to the next instruction since instructions and data are both stored in memory, the control unit must recognize where a sequence of instructions begins and ends for our simulator, we will assume that programs start at address 0 and end with a HALT instruction in real computers, the operating system must keep track of program locations
250
Program Execution example: machine language program for adding two numbers in memory program execution: program counter is initialized: PC = 0 instruction at memory location 0 is fetched, PC is incremented to 1 instruction is decoded and CPU cycle is executed: load contents of memory location 5 into RO next instruction is fetched at location 1, PC is incremented to 2 instruction is decoded and CPU cycle is executed: load contents of memory location 6 into R1 next instruction at memory location 2 is fetched, PC is incremented to 3 instruction is decoded and CPU cycle is executed: add contents of R0 and R1, store result in R2 next instruction at location 3 is fetched, PC is incremented to 4 instruction is decoded and CPU cycle is executed: copy contents of R2 into memory location 7 next instruction at location 4 is fetched, PC is incremented to 5 instruction is decoded and CPU cycle is executed: halt instruction program ends
251
Complete Computer Simulator
we can extend the simulator to integrate a control unit, containing Program Counter (PC) for keeping track of the next statement Instruction Register (IR): for storing fetched instructions the user can enter a sequence of instructions directly into memory, starting at address 0 and ending with a Halt instruction any data to be acted upon is stored in additional memory locations when the user clicks execute, the program instructions are executed in sequence
252
Computer Simulator Example
here, the program consists of 5 instructions, stored in addresses 0 – 4 data values are stored in addresses 5 & 6 before execution, the PC = 0
253
Simulator Example (cont.)
when execution begins, the instruction at address 0 is fetched and decoded the CPU hardware is configured as specified (here, to copy data from address 5 to R0) PC is incremented a datapath cycle is executed
254
Simulator Example (cont.)
next, the instruction at address 1 is fetched and decoded the CPU hardware is configured as specified (here, to copy data from address 6 to R1) PC is incremented a datapath cycle is executed
255
Simulator Example (cont.)
next, the instruction at address 2 is fetched and decoded the CPU hardware is configured as specified (here, to add R0 and R1 and store the sum in R2) PC is incremented a datapath cycle is executed
256
Simulator Example (cont.)
next, the instruction at address 3 is fetched and decoded the CPU hardware is configured as specified (here, the value in R2 is copied to address 7) PC is incremented a datapath cycle is executed
257
Simulator Example (cont.)
next, the instruction at address 4 is fetched and decoded the CPU hardware is configured as specified (here, Halt) PC is incremented execution halts
258
The Role of I/O Devices recall: input/output devices enable the user to interact with the computer input devices – keyboards, mice, scanners, … output devices – display screens, speakers, printers, … the first programmable computers (1950s) and personal computers (1970s) were designed to execute one program at a time the user entered program instructions and data directly into main memory via input devices the user instructed the CPU to fetch program instructions and execute them in sequential order the user viewed results by sending the contents of the memory to an output device most modern computers allow for multitasking (multiple programs can be active simultaneously) instructions and data associated with each program must be loaded into separate portions of main memory when control switches from one program to another, the CPU must save the state of the current program and locate the portion of memory for the new program memory partitioning and control switches are managed by the operating system
259
Machine vs. Assembly Language
programming in machine languages is difficult and tedious machine code is nearly impossible to understand and debug assembly languages were developed in the early 1950s to simplify programming assembly languages allow for words to substitute for bit patterns also, allow for variable names instead of numerical addresses
260
Assembly Language Example
the stored-program computer simulator allows the user to enter instructions in assembly language can even toggle the view from assembly language to machine language using the "View As:" pull-down menu to the left of each memory location
261
Chapter 15 JavaScript Strings
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 15 JavaScript Strings
263
Strings as Objects so far, your interactive Web pages have manipulated strings in simple ways use prompt or a text box/area to input a word or phrase store that text in a (string) variable incorporate the text in a message, possibly using + to concatenate strings are different from numbers and Booleans in that they are objects a software object is a unit of code that encapsulates both data and operations that can be performed on that data a string is a software object that models words and phrases data: a sequence of characters, enclosed in quotes operations include: make upper case, make lower case, determine the number of characters, access a particular character, search for a particular character, …
264
Object-Oriented Programming
objects are fundamental in the dominant approach to developing software systems: object-oriented programming (OOP) OOP encourages programmers to design programs around software objects the programmer identifies the real-world objects involved in a system (e.g., for a banking program: bank account, customer, teller, …) then designs and builds software objects to model these real-world objects OOP is effective for managing large systems, since individual objects can be assigned to different teams and developed independently OOP also supports code reuse, since the same or similar objects can be combined in different ways to solve different kinds of problems example: a doorbell button has physical components/properties: color, shape, label, … has functionality: when you press the button, the bell rings an HTML button is a software object that models a real-world button has functionality: when you click on the button, JavaScript code is executed
265
Properties and Methods
using object-oriented terminology, the characteristics of an object are called properties e.g., a string object has a length property that identifies the number of characters in the string the operations that can be performed on the string are called methods e.g., the toLowerCase method makes a copy of the string with all upper-case letters converted to lower-case properties and methods are not new concepts a property is a special kind of a variable (it stores a value) a method is a special kind of function (it performs some action) what is special is that they are associated with (or "belong to") an object e.g., each string object will have its own variable to stores it length to access an object property, specify: object name, a period, property name str1 = "foo"; str2 = "Hi there"; len1 = str1.length; len2 = str2.length;
266
Properties and Methods
similarly, to call a method: object name, period, method call e.g., str.toLowerCase() calls the toLowerCase method on str (which returns a lowercase copy of the string) e.g., str.toUpperCase() calls the toUpperCase method on str (which returns an uppercase copy of the string) note: the toLowerCase and toUpperCase methods do not change the string object they are called on (only an assignment can do that!) instead, they return modified copies of the string
267
String Manipulation Page
268
Common String Methods useful methods exist that allow programmers to access and manipulate individual components of a string components are identifiable via indices, or numbers that correspond to the order in which individual characters occur in a string indices are assigned in ascending order from left to right, so that the first character in the string is at index 0 the charAt method provides access to a single character within the string it takes an index as an input and returns the character at that particular index word = "foo"; ch = word.charAt(0); // ASSIGNS ch = "f" the substring method provides access to an entire sequence of characters within the string it takes two numbers as inputs, representing the starting (inclusive) and ending (exclusive) indices of the substring, and returns the substring word = "foo"; sub = word.substring(1, 3); // ASSIGNS sub = "oo"
269
String Access/Concatenation
recall: the concatenation operator (+) can join strings together assuming the variable word stores a string value, what affect would the following assignment have? word = word.charAt(0) + word.substring(1, word.length); the following function takes a string as input and uses string method calls to create (and return) a capitalized version of that string
270
Searching Strings the search method traverses a string in order to locate a given character or substring it takes a character or string as input and returns the index at which the character or string first occurs (or -1 if not found) str = "banana"; num1 = str.search("n"); // ASSIGNS num1 = 2 since the character // "n" first occurs at index 2 num2 = str.search("ana"); // ASSIGNS num2 = 1 since the string // "ana" first occurs at index 1 num3 = str.search("z"); // ASSIGNS num3 = -1 since the character // "z" does not occur anywhere simple application: determine whether a string is a single word or a phrase if the string contains no spaces, the call str.search(" ") will return -1, indicating that the string value consists of a single word if str.search(" ") returns a nonnegative value, then the presence of spaces signifies a phrase containing multiple words
271
General Searches there are times when you want to search for a type of character, rather than a specific value example: converting a word into Pig Latin if a word contains no vowels or begins with a vowel, the characters “way” are appended to the end of the word nth nthway apple appleway if a word begins with a consonant, its initial sequence of consonants is shifted to the end of the word followed by “ay” banana ananabay cherry errychay in order to distinguish between these two cases, must search for the first vowel then, use the substring method to break the string into parts and the + operator to put the pieces back together (with "ay") cherry erry + ch + ay = errychay
272
General Searches rather than having to search for vowels individually, an entire class of characters can be specified using /[ ]/
273
Strings and Repetition
some tasks involve repeatedly performing the same operations to accomplish such tasks, we can combine while loops with string methods such as charAt and search example: a while loop used to access and process each character in a string the characters that comprise the string are concatenated one-by-one onto another string, resulting in an exact copy
274
Chapter 16 Inside the Computer – Transistors and Integrated Circuits
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 16 Inside the Computer – Transistors and Integrated Circuits
276
Electricity and Switches
modern 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 computer screen, illuminating the individual pixels that make up images and letters electricity runs the motor that spins the hard-drive 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 electrical current along a wire
277
Electricity Basics electricity is a flow of electrons, the negatively charged particles in atoms, through a medium good conductors of electricity allow for the flow of electrons with little resistance (e.g., copper, silver, gold) other elements, especially nonmetals, are poor conductors (e.g., carbon, oxygen) electricity can be quantified in amperes or voltage amperes gauge electron flow: 1 amp is equal to 6.24 quintillion electrons flowing past a given point each second voltage measures the physical force produced by the flow of electrons: standard household in United States has 110 to 120 volt outlets
278
Switches the most basic tool for controlling the flow of electricity is a switch a switch can be flipped to connect or disconnect two wires, thus regulating the flow of electricity between them example: a light switch on a wall serves as an intermediary between the power line entering your home and the outlet that operates a lighting fixture if the switch is turned on, then the wires that link the outlet to the power line are connected, and the lighting fixture receives electricity if the switch is turned off, then the connection is interrupted, and no power reaches the outlet
279
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 on/off positions were controlled by the voltage to a magnet 1940’s – vacuum tubes replaced relays, which were faster (since no moving parts) but tended to overheat and burn out frequently 1948 – the transistor was developed by Bardeen, Brattain, and Shockley a transistor is a solid piece 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 semiconductors are metals that can be manipulated to be either good or bad conductors of electricity the first transistors were made of germanium and gold, but modern transistors are constructed from silicon through a process known as doping, impurities are added to a slab of silicon, causing the metal to act as an electrical switch
280
Transistors as Switches
a PMOS transistor is positively doped, so that the switch is "closed" when there is no current on the control wire, but "opens" when current is applied an NMOS transistor is negatively doped, so that the switch is "open" when there is no current, but "closes" when there is current
281
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 example: consider the following circuit combining two transistors if no current (0 volts) is applied to the input wire, the PMOS transistor will close to allow current to travel on the output wire, and the NMOS transistor will open to disconnect the ground if current (5 volts) is applied to the input wire, the PMOS transistor will open to disconnect the output wire, and the NMOS transistor will close to ground the input the end result is that the output is the opposite of the input this circuit known as a NOT gate
282
Gates and Binary Logic the term “gate” suggests a simple circuit that controls the flow of electricity in the case of a NOT gate, the flow of electricity is manipulated so that the output signal is always opposite of the input signal we can think of a gate as computing a function of binary values 0 represents no current; 1 represents current the symbol to the left (triangle w/ circle) is often used to denote a NOT gate the truth table to the right describes the mapping of input to output note: NOT gates invert voltages in the same way that the JavaScript NOT operator (!) inverts Boolean values 0 corresponds to false; 1 corresponds to true
283
Gates and Binary Logic many other simple circuits can be defined to perform useful tasks AND gate – produces voltage on its output wire if both input wires carry voltage OR gate – produces voltage on its output wire if either input wire carries voltage AND, OR, and NOT gates can be combined to construct all the circuitry required to store and manipulate information within a computer
284
From Gates to Circuits transistors are connected to form basic logic gates, which are then combined to build more advanced circuitry example: adding two binary numbers we can represent a 4-bit binary number using 4 wires current on a wire signifies a 1 bit for that place; no current signifies 0
285
Half-adder Circuit recall the rules of binary addition:
although binary addition is relatively straightforward, designing a circuit for adding binary numbers is quite complex instead of starting at the transistor level, we can use AND, OR, and NOT gates focus first on the addition of 2 bits requires two input lines, two output lines (sum of inputs and possible carry) the circuit consist of four gates (known as a half-adder)
286
Full-adder Circuit the term “half-adder” refers to the fact that when you add binary numbers containing more than one bit, summing the corresponding bit pairs by column is only half the job you must also consider that a bit might be carried over from the previous addition using half-adders and logical gates as building blocks, we can design a circuit that takes this into account (known as a full-adder)
287
4-bit Adder Circuit using full-adders as building blocks, we can design a more complex circuit that sums two 4-bit numbers since a full-adder is required to add each corresponding bit pair together (along with possible carry), the circuit will need four full-adders wired together
288
Designing Memory Circuitry
main memory and registers within the CPU are composed of circuitry whereas adders manipulate inputs to produce outputs, memory circuits must maintain values over time the simplest circuit for storing a value is known as a flip-flop it can be set to store a 1 by applying current on an input wire it can be reset to store a 0 by applying current on another input wire
289
Flip-flop Circuit a flip-flop stores a value by feeding the output currents back into the circuit the value is maintained by current flowing around and around the circuit a current on the Set wire produces current on the output, which then cycles a current on the Reset wire produces no current on the output
290
From Circuits to Microchips
initially, circuits were built by wiring together individual transistors this did not lend itself to mass production it also meant that even simple circuits consisting of tens or hundreds of transistors were quite large (to allow space for human hands) in 1958, two researchers (Jack Kilby and Robert Noyce) independently developed techniques that allowed for the mass-production of circuitry circuitry (transistors + connections) is layered onto a single wafer of silicon, known as a microchip since every component is integrated onto the same microchip, these circuits became known as integrated circuits
291
Manufacturing ICs the production of integrated circuits is one of the most complex engineering processes in the world transistors on chips can be as small as .065 microns (roughly 1/1,500th the width of human hair) since a hair or dust particle can damage circuitry during manufacture, chips are created in climate-controlled "clean rooms"
292
Manufacturing ICs to produce the incredibly small and precise circuitry on microchips, manufacturers use light-sensitive chemicals initially, the silicon chip is covered with a semiconductor material, then coated with a layer of photoresist (a chemical sensitive to UV light) transistors are then printed onto a mask (transparent surface on which an opaque coating has been applied to form patterns) UV light is filtered through the mask, passing through the transparent portions and striking the surface of the chip in the specified pattern the photoresist that is exposed to the UV light reacts, hardening the layer of the semiconductor below it the photoresist that was not exposed and the soft layer of semiconductor below are etched away, leaving only the desired pattern of semiconductor material on the surface of the chip the process can be repeated times depositing multiple layers
293
Packaging Microchips since a silicon chip is fragile, the chip is encased in plastic for protection metal pins are inserted on both sides of the packaging, facilitating easy connections to other microchips impact of the microchip lower cost due to mass production faster operation speed due to the close proximity of circuits on chips simpler design/construction of computers using prepackaged components Moore’s Law describes the remarkable evolution of manufacturing technology Moore noted that the number of transistors that can fit on a microchip doubles every 12 to 18 months this pattern has held true for the past 30 years industry analysts predict that it will continue to hold for the near future
294
Chapter 17 JavaScript Arrays
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 17 JavaScript Arrays
296
Arrays as Objects earlier, we introduced the concept of software objects: programming structures that encompass both data (properties) and operations (methods) e.g., a string object has properties (e.g., length) and methods (e.g., charAt) that enable the programmer to easily store and manipulate text like strings, JavaScript arrays are objects that encapsulate multiple values and their associated properties and methods unlike strings (which store only text characters), the items in an array can be of any data type an array consists of a sequence of items, enclosed in square brackets and separated by commas when assigning values to arrays: an item can appear in an array more than once array items can be specified as expressions arrays can be empty
297
Accessing Items in an Array
since an array stores a series of values, its associated memory cell can be envisioned as divided into components, each containing an individual value array items are assigned sequential indices, allowing programmers to identify an item by its corresponding index array access is accomplished by specifying the name of the array object, followed by the index of the desired item in brackets the first item is misc[0], the second is misc[1], …, the last is misc[length-1] if an index is specified beyond the scope of an array, the access yields undefined
298
Array Access Example we now can understand how the RandomOneOf function from random.js works the input to the function is a nonempty array of arbitrary items the RandomInt function is called to pick a random index from the array (between 0 and the last index, list.length-1) the bracket notation is used to access the item at that index, which is then returned by the function
299
Assigning Items in an Array
array items can be assigned values just like any variable suppose the array misc has been assigned to store the following the assignment misc[0] = would store the value 1000 as the first item in the array, overwriting the value that was previously there if the index in an assignment statement is beyond the array’s current length, the array will automatically expand to accommodate the new item the assignment misc[8] = "oops" would store "oops" at index 8
300
From Strings to Arrays so far, our Web pages have handled each input from the user as a single string this approach is limiting since many programming tasks involve separately processing an arbitrary number of words or numbers entered by the user recall the Pig Latin page we might want to generalize the page so that it translates entire phrases instead of just words that is, the user would enter an arbitrary sequence of words and each word would be translated this task would be very difficult using our current set of programming tools
301
String split Method JavaScript strings provide a method, split, for easily accessing the components of a string the only input required by the split method is a character (or sequence of characters) that serves as a delimiter for breaking apart the string the split method separates the string into component substrings at each occurrence of the delimiter, and returns an array consisting of those substrings user = "Grace Murray Hopper"; arr1 = user.split(" "); // ASSIGNS arr1 to be the array // ["Grace", "Murray", "Hopper"] as was the case with strings, /[ … ]/ can be used to specify groups of characters
302
Example: Generating Acronyms
one interesting application of the split method is in deriving acronyms acronyms (terms made from the first letters of words in a phrase) are especially popular in the computing field RAM – Random Access Memory GUI – Graphical User Interface WWW – World Wide Web the Acronym function takes a phrase, such as "What you see is what you get", splits it into an array of individual words, then extracts the first letters to construct the acronym
303
Acronym Page the Acronym function can be integrated into a Web page
the user enters a phrase in a text area a button is defined to call the Acronym function with the text box contents as input the result returned by the function call is displayed in another text box
304
Arrays of Numbers some applications involve reading and manipulating sequences of numbers e.g., suppose we wanted to calculate the average of some number of grades we could enter the numbers in one big string, separated by spaces, then use the split function to separate out the individual numbers then, traverse the resulting array and calculate the sum and average of the numbers note: even if the input string contains numerical digits, split returns each array item as a string (similar to prompt and text box/area access) we can write a function to traverse the array and convert each item to a number
305
Average Page this page averages an arbitrary number of grades (entered as a string in a text box) note: ParseArray is defined in the library file array.js
306
Example: Grades this page can be generalized to enter different types of grades for a course the average for each type of grade could be calculated (as before) then, those averages could be combined for a weighted course average & letter grade
307
Example: Dice Stats recall our web page for simulating repeated dice rolls and recording the number of times that a specific total was obtained statistical analysis predicts that, given a large number of dice rolls, the distribution of totals will closely mirror the percentages listed below
308
Approach 1: Separate Counters
to obtain a valid distribution of dice totals, we would need to simulate a large number of rolls and simultaneously count the occurrences of every total this can be accomplished by defining 11 counters, each corresponding to a particular total however, this would be extremely tedious requires separate assignment statements for all 11 counters requires a cascading if-else statement with 11 cases not easily generalized – what if we wanted to use 8-sided dice?
309
Approach 2: Array of Counters
instead of representing each counter as a separate variable, we can define the counters as items in an array all 11 counters can be stored in an array and initialized via a single assignment statement any individual counter can be accessed and updated via its corresponding index since the first possible total is 2, its count is stored in index 0 the next possible total, 3, has its count stored in index 1 … for an arbitrary roll, its count is stored in index roll-2 the resulting code is shorter, simpler, and easier to generalize
310
Dice Stats Page code for maintaining statistics on repeated dice rolls can be integrated into a Web page the number of rolls to be simulated is entered by the user into a text box a button is defined to call the code for repeatedly simulating the roll and maintaining stats, with the text box contents as input the numbers of rolls for each total are then displayed in a (scrollable) text area
311
Chapter 18 Computers and Society
A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 18 Computers and Society
313
Positive Impact of Technology
historian Larry Gormley ranked technological developments according to their impact on modern life do you agree with his list? (Gormley, Larry. “The Greatest Inventions in the Past 1000 Years.” eHistory.com, 2003.)
314
Positive Impact of Technology
more than any other invention, computer technology is still evolving, which means that it continues to impact society in new ways the first electronic computers made significant contributions in the 1940’s COLOSSUS – used for code breaking in World War II ENIAC – performed calculations and simulations that led to the development of nuclear technology and Cold War science currently, we live in an "information economy", with computers central to business and innovation technology has become so pervasive in daily life, it is difficult to imagine life without it e.g., monetary transactions cash is frequently being replaced with credit or debit cards computerized banking networks enable the immediate electronic transfer of funds ATM machines allow people to access their money around the clock from any location all this has discouraged traditional theft, but has inspired new forms of illegal activity
315
Computers in Everyday Tasks
modern life also depends on thousands of less obvious, hidden computer applications embedded processors are computer chips that are built into appliances and machinery to control their workings they account for more than 90% of all computer processors the average U.S. home contains 50 to 100 embedded processors (2001 est.) in ovens, television remote controls, cordless phones, automatic thermostats, … automobiles employ embedded processors to control a wide variety of components (Webb,Warren.“Embedded Technology Transforms the Automobile.” EDN Magazine, 1999.)
316
Computers in Everyday Tasks
society has also been affected by the availability of personal computers and easy-to-use software software can enable people to accomplish tasks previously reserved for highly trained professionals, e.g., word processing and desktop publishing software video editing software tax preparation software
317
Internet/Web for Information
many users utilize the Internet/Web as an information source online resources are quickly replacing (or complementing) traditional sources of information Web sites can be updated 24 hours a day allowing publishers to report stories as soon as they break text can be integrated with other types of media the immediacy of online delivery system is especially appealing in order to compete, many newspapers and magazines have expanded their offerings to include online versions e.g.,
318
Internet/Web for Information
traditional media have approached the Internet in a variety of ways some provide limited services online for free e.g., cnn.com, weather.com others provide full services with a fee e.g., Encyclopedia Britannica sells access over the Web independent media organizations have utilized the Web to present stories and opinions that might not otherwise reach a mainstream audience
319
Internet/Web for Information
the majority of Web pages are unique resources created by individuals and private organizations you can find Web content on virtually any topic to help navigate the vast sea of information, search engines automatically catalog Web pages and allow users to search for data by topic or keywords
320
Internet/Web for Communication
many users were originally drawn to the Internet by the availability of electronic mail and newsgroups in 2006, 91% of all Internet users communicated via 171 billion messages were sent and received each day 70% of those s were spam Internet Service Providers (ISPs) manage accounts with other services e.g., AOL, msn, Microsoft Hotmail, Yahoo! Mail programs such as Microsoft Outlook provide an intuitive user interface for sending and receiving messages
321
Internet/Web for Communication
more recently, the Internet has popularized the use of instant messaging enables users to type text messages and view responses immediately in the same window in effect, they can conduct personal conversations online 53 million users sent instant messages during February 2004 of those, 24% claimed to use IM more frequently than
322
Internet/Web for Commerce
another popular function of the Web is to facilitate electronic commerce, or e-commerce businesses have recognized the Web’s potential as an advertising medium, and as a tool for reaching new customers some business sites are information-based (providing background on the company or product descriptions) other business sites are transaction-based (allowing customers to purchase products or services directly) online shopping has numerous advantages for the consumer you can make purchases from your home at any time it is easy to comparison shop many online retailers, such as Amazon.com, allow consumers to research products as well as purchase them
323
Internet/Web for Commerce
total online sales in 2006: $108 billion many of the most successful sites are online offshoots of traditional retailers Barnes & Noble, Sears, Circuit City companies that are strictly Internet ventures have added risks due to their lack of other revenue streams for startup and development many of these companies fail early on, however, some are very successful Amazon.com: $10.7 billion in sales in 2006
324
Internet/Web for Commerce
the Web has provided a new advertising channel for businesses and organizations e-commerce sites charge fees for hosting advertising banners on web pages banner ads are clickable images that promote a particular company’s product or service users who click on a banner ad are typically directed to the company’s Web site, where they can make purchases or review product-related information the Web’s structure allows for a direct connection between ads and related purchasing interfaces in addition, the Internet is extensively used for communication and information exchanges within and among businesses business-to-business (B2B) transactions allow companies to manage inventory more dynamically can improve efficiency by linking various data channels (e.g., sales & marketing) businesses may form partnerships based on sharing resources and information
325
Potential Dangers in conjunction with the benefits we have mentioned, the widespread adoption of technology also introduces the potential for abuses and undesirable consequences potential dangers to individuals, businesses, and society at large include an over-reliance on complex, perhaps poorly-understood, systems information overload privacy and security violations the Digital Divide
326
Reliance on Complex Systems
as society becomes dependent on complex, computer-based products and services, the effects of errors or system failures become far-reaching computer-system bugs can produce dire consequences between 1985 and 1987, six cancer patients received massive radiation overdoses due to equipment malfunction, resulting in four deaths (the malfunction was traced to a single coding error) in 1990, AT&T’s long-distance telephone network was down for nine hours due to a misplaced statement in the electronic switching software (60,000 customers were without service, resulting in $60 million of lost revenue) in 1991, 28 soldiers were killed by a Scud missile because a software error caused the Patriot missile to miss its target in 1999, NASA’s Mars Climate Orbiter went off course and was destroyed in the Martian atmosphere (the problem was due to software inconsistencies which used different measurement conversions, e.g., English vs. Metric) to avoid errors, various software design and testing methodologies are used however, as the size and complexity of the software grows, design and testing become exponentially more difficult Windows 2000 – 35 million lines of code, 63,000 known bugs
327
Information Overload the impressive range of information available online can be viewed as a strength, but it is also one of the greatest weaknesses often, data is not well organized finding a single piece of specific information can be very difficult as of April 2005, Google claimed to have cataloged more than 8 billion pages search engines are helpful in narrowing down Internet searches, but users must be careful in selecting search criteria a Google search for “JavaScript” produced 425 million matches a more refined search for “JavaScript prompt function” produced 924,000 matches even after a user locates a Web page related to the desired topic, judging reliability is not always easy the Web is neither monitored or censored authors may provide incomplete, uninformed, or biased answers
328
Information Overload since most Internet/Web content lacks editorial review, it is up to the user to evaluate its credibility common criteria for evaluating credibility include:
329
Privacy and Security when using credit cards or shopping online, consumers sacrifice privacy for the sake of convenience companies maintain records of consumer purchases private details can be inferred from shopping patterns companies often sell customer profiles to marketing firms Web users can limit exploitation by interacting only with reputable online businesses with privacy policies such policies will explain what information is collected by the business and how that information is to be used (and shared)
330
Privacy and Security email also raises privacy concerns
when a message is received it is commonly stored in a file on the recipient’s computer there is a danger that unauthorized users might get access to that file few laws apply directly to electronic privacy courts overwhelmingly favor employers over employees in privacy suits unless explicitly stated, it is generally accepted that employers may access any content on company-owned machines privacy is closely linked with security messages travel through numerous routers, and each router represents a security risk, because someone could gain access to a router and eavesdrop on a relayed message with online transactions, credit card numbers or other personal information can be intercepted and subsequently result in identity theft encryption methods are commonly used to secure information transmissions, but online fraud is still a continuing problem
331
The Digital Divide an especially troubling aspect of recent technological developments is that the benefits associated with computers are not shared by all Americans with minority ancestry, lower incomes, and less education are far less likely to be online (Pew Internet and American Life Project: Latest Trends. Pew Research Center, December 2006.)
332
The Digital Divide addressing the digital divide
during the Clinton administration, public schools received government funding for computer technology and Internet service by 2003, nearly all public schools were connected to the Internet, as compared to 35% in 1994 most public libraries and community centers provide Internet-enabled computers organizations such as CompuMentor supply Internet access and technical assistance to minority groups and low income individuals the digital divide is still a problem for Americans, but there is no doubt that conditions have improved the digital divide also exists on a global scale America, Western Europe, and certain Asian countries have much greater Internet connectivity than other parts of the world lack of Internet access places less developed nations at a significant disadvantage, and compounds other economic problems the United Nations, World Economic Forum, and other organizations are working to address the global digital divide
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.