# collections

id: 324d47be-ad32-4a1e-9705-fc4b5d133163
name: langchain
database_id: 00000000-0000-0000-0000-000000000000
config_json_str:
{"hnsw_configuration": {"space": "l2", "ef_construction": 100, "ef_search": 10, "num_threads": 2, "M": 16, "resize_factor": 1.2, "batch_size": 100, "sync_threshold": 1000, "_type": "HNSWConfigurationInternal"}, "_type": "CollectionConfigurationInternal"}


# embedding_metadata

key: chroma:document
string_value:
1
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., email, Web browsing, document processing)
◼ laptop computers: similar functionality to desktops, but mobile
◼ palmtop computers: portable, but limited applications and screen size
◼ smartphones: portable, integrated with phone, camera


key: chroma:document
string_value:
2
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 2020
◼ 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


key: chroma:document
string_value:
3
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


key: chroma:document
string_value:
4
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
1. Input/Output Devices (I/O) allow the user to interact with the computer
2. Memory stores information to be processed as well as programs (instructions 
specifying the steps necessary to complete specific tasks)
3. Central Processing Unit (CPU) carries out the instructions to process information


key: chroma:document
string_value:
5
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: AMD Ryzen 5, Intel Core i5, and Intel Core i7


key: chroma:document
string_value:
6
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)
 but they vary across CPUs, higher end can do more in a single instruction
◼ complex behavior results from incredible speed
 a 2.6 GHz AMD A6 processor can execute 2.6 billion instructions per second
 a 3.3 GHz Intel i9 processor can execute  3.3 billion instructions per second
a dual-core processor contains 
the circuitry of 2 processors, 
packaged on a single chip
• in theory, can execute 2 
instructions simultaneously
a deca-core processor contains 
the circuitry of 10 processors, 
packaged on a single chip
• in theory, can execute 10 
instructions simultaneously


key: chroma:document
string_value:
7
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


key: chroma:document
string_value:
8
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)


key: chroma:document
string_value:
9
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, flash drive, compact disk (CD)
RAM chips        hard drive         flash drive          CD/DVD


key: chroma:document
string_value:
10
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


key: chroma:document
string_value:
11
Input/Output (I/O)
input devices allow the computer to receive data and instructions from 
external sources
◼ examples: keyboard, mouse, track pad, touch screen, microphone, scanner
output devices allow the computer to display or broadcast its results
◼ examples: monitor, speaker, printer


key: chroma:document
string_value:
12
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, Flash)
◼ e.g., Web browsing (Microsoft Edge, Mozilla Firefox, Google Chrome, Safari)


key: chroma:document
string_value:
13
Operating Systems
the Operating System (OS) is a collection of programs that controls how the             
CPU, memory, and I/O devices work together
◼ kernel: manages the CPU's operations, controls how data and instructions are 
loaded and executed by the CPU, coordinates other hardware components
◼ file system: organizes and manages files and directories
◼ graphical user interface (GUI): provides intuitive, visual elements for interacting 
with the computer
 GUI's utilize windows, icons, menus, and pointers


key: chroma:document
string_value:
HTML & Web Pages
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 (<>)
1


key: chroma:document
string_value:
HTML Tags
required tags in a Web page:
◼ <!doctype html> tells the browser this is 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
2


key: chroma:document
string_value:
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
<!-- simple.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
3


key: chroma:document
string_value:
Text Layout & Formatting
extra white space (spaces, tabs and blank lines) is 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 &nbsp; special symbol forces a space to appear in the text
you can specify some text formatting using other HTML elements
◼ a b element (<b>…</b>) specifies bold text
◼ an i element (<i>…</i>) specifies italicized text
◼ a u element (<u>…</u>) specifies underlined text
◼ a sup element (<sup>…</sup>) specifies superscripted text
◼ a sub element ( <sub>…</sub> ) specifies superscripted text
4


key: chroma:document
string_value:
Sections
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 
◼ <h2> … </h2> enclose a Sub-heading 
.
.
.
◼ <h6> … </h6> enclose a  Sub-sub-sub-sub-sub-heading
the horizontal-rule element <hr> draws a dividing line in the page
6


key: chroma:document
string_value:
Styling Elements
Web browsers rely on user preferences when displaying a page 
◼ each browser has a set of default (language, font, text size, color scheme), 
which can be reset by the user
◼ can override some of these defaults by adding STYLE attributes
an attribute is qualifier that can be added to an element in its opening tag
◼ the style attribute can be used to set style properties for an element
style="PROPERTY:VALUE"
e.g., can change the text color for an element by setting the color property
<p style="color:red"> Here is some red text. </p> 
8


key: chroma:document
string_value:
BODY Styling
when a style property is assigned to the body element, it applies to all 
elements embedded in the page
<body style="color:darkblue"> 
  ENTIRE PAGE APPEARS IN DARK BLUE TEXT
 </body> 
the background-color property can also be set for the entire page
<body style="background-color:lightgray"> 
  ENTIRE PAGE APPEARS WITH LIGHT GRAY BACKGROUND
 </body> 
can set multiple properties in the same style attribute
<body style="background-color:gray; color:white"> 
  ENTIRE PAGE APPEARS WITH GRAY BACKGROUND, WHITE TEXT
 </body> 
9


key: chroma:document
string_value:
SPAN & DIV
in addition to p, the span and div elements are useful for grouping text
◼ span specifies a short span of text embedded in a paragraph
◼ div specifies a page division which groups multiple elements together
span can be used to embedded colored words or phrases 
 <p>Isn't this page <span style="color:red">colorful</span>?</p>
div can be used to group paragraphs and color them as one
<div style="color:white">
  <p>   
    You can format multiple paragraphs at once by placing them 
    inside a DIV and setting the STYLE attribute of the DIV. 
  </p>
  <p>Both of these paragraphs will have white text.</p>
</div>
10


key: chroma:document
string_value:
Font Styling
the font-family property can override the default font typeface
◼ must specify the font name and its family (as a backup)
 <p style="font-family:Helvetica, sans-serif">
   This text appears in Helvetica.
 </p>
   <p style="font-family:Times, serif">This text appears in Times.</p>
the font-size property can override the default size of the font
◼ can be absolute (in pixels) or relative to the current size (as percentage)
 <span style="font-size:20px">This text appears 20 pixels tall.</span>
 
 <p style="font-size:150%">This text is 50% larger than normal.</p>
12


key: chroma:document
string_value:
Alignment Styling
the text-align property can set the alignment of text elements
 <h2 style="text-align:center">Centered Heading</h2>
 <h2 style="text-align:right">Right-Justified Heading</h2>
 <h2 style="text-align:justify">Left- and Right-Justified Heading</h2>
the text-indent property indents the first line of a paragraph
 <p style="text-indent:10px">A paragraph with the 1st line indented...</p> 
the margin-left and margin-right properties indent the entire paragraph
 <p style="margin-left:10px">A paragraph with all lines indented...</p>
14


key: chroma:document
string_value:
Web ≠ Internet
people often confuse the Web and the Internet – they are not the same! 
◼ Internet was created in 1969; World Wide Web was created in 1990
1
the Internet could exist without the Web 
◼ and did, in fact, for many years (applications included email and news groups)
the Web couldn't exist without the Internet
◼ the Internet is the hardware that stores and executes the Web software


key: chroma:document
string_value:
History of the Web
CERN researchers were spread across Europe, but needed to collaborate
◼ in 1989, Berners-Lee devised a system that would allow them to freely 
exchange data, regardless of location or computer type
his design integrated two key ideas
1. hypertext (documents with interlinked text and media)
 Web pages can contain images and links to other pages
2. the distributed nature of the Internet
 pages can be stored on machines all across the Internet
 logical connections between pages are independent of physical locations 2
World Wide Web was invented by 
Tim Berners-Lee
◼ researcher from 1984-1994 at 
the European Laboratory for 
Particle Physics (CERN)
◼ founded and serves as director of 
the World Wide Web Consortium 
(W3C)
◼ knighted by Queen Elizabeth in 
2004


key: chroma:document
string_value:
Web Timeline
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 at 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) 
2021: Google Chrome has ~63% of market, then Safari at 19%, Mozilla Firefox at 4%
in 2019, Google claimed to have 
indexed more than 130 trillion 
pages
 
others estimate the number of 
Web pages could be in the 
hundreds of quadrillions
3


key: chroma:document
string_value:
Search Engines
as the Web grew, it became difficult to find resources
◼ in general, you needed to somehow know the address of a page to access it
manually generated index sites appeared in the early 1990s
◼ provided lists of popular Web sites, organized by topic or alphabetically
◼ these were not scalable as the Web exploded in size
the first Web search engines appeared in the mid 1990s
◼ used software called Web crawlers, or spiders, to surf the Web, indexing pages
◼ enabled users to search those indexed pages via search words or phrases
unfortunately, the quality of early searches was not very good
◼ the search for a word/phrase might return unrelated or unreliable pages
4
the Google search engine began in 1996 as a 
research project by Stanford grad students 
Larry Page and Sergey Brin
◼ their goal was to create an easy-to-use search 
engine that produced high-quality results
◼ founded Google Inc. in 1998


key: chroma:document
string_value:
Google
at the heart of Google's performance is the PageRank algorithm
◼ ranks pages based on their perceived value and trustworthiness
◼ if a page is linked to by many other pages, that suggests that many people find 
its contents valuable and trustworthy
◼ moreover, the more valued/trusted those linking pages are, the more impact 
their links will have 
Brin & Page also revolutionized how browsers made money
◼ they sold targeted adds and charged based on clickthrough
◼ e.g., a shoe store could purchase adds for when a user entered "shoe" or 
"footwear" as search terms, and would be charged based on how often users 
clicked on the ads
Brin & Page donated the patent for the PageRank algorithm to Stanford
◼ licensed its use back for $336 million in stock
5
Google dominates the search market
▪ performed 5.6 billion searches in 2020
▪ that's 63,000 searches per second!


key: chroma:document
string_value:
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
6


key: chroma:document
string_value:
Web Server
a Web server is an Internet-enabled computer that executes software for 
providing access to certain Web document 
◼ it stores Web pages and files (images, videos, …) and sends them to browsers who 
request them
7


key: chroma:document
string_value:
Web Addresses
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
8


key: chroma:document
string_value:
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
9


key: chroma:document
string_value:
Web Protocols: HTML
HyperText Markup Language (HTML) utilizes tags to markup page contents
◼ these tags tell the browser how to display the contents
◼ HTML5 is the current standard, supported by all browsers
10


key: chroma:document
string_value:
Web Protocols: HTTP
HyperText Transfer Protocol 
(HTTP) defines how messages 
between browsers and servers 
are formatted
◼ the prefix http:// in a URL 
specifies that the HTTP 
protocol is to be used in 
communicating with the 
server
◼ the prefix https:// is 
similarly used for secure 
(encrypted) HTTP 
communications
11


key: chroma:document
string_value:
Browser caching
for efficiency reasons, browsers will sometimes cache pages/images
◼ the browser reserves space (a cache folder) on the user's computer
◼ to avoid redundant downloads, the browser will store a copy of a page/image in 
that reserved space (along with a timestamp)
◼ the next time the page/image is requested, browser will send a timestamp of the 
cached copy
 the server compares that timestamp with one of the stored document
▪ if cached copy is newer, then response says to use it
▪ if server copy is newer, then response includes the new version
in general, browsers are not allowed to access/modify user files
◼ this is for safety – you don't want to visit a Web site and risk having your files 
copied or damaged
◼ caching is a loophole (can only access/modify files in cache folder)
NOTE: caching still requires the browser to contact the server 
▪ but only have to download the page if it has changed since last cached
12


key: chroma:document
string_value:
Cookies
another loophole is cookies
a cookie is a small file that can be stored and accessed by a Web server
◼ similar to caching, browsers reserve space (a cookie folder) on the user's 
computer
◼ when the user visits a site, the Web server is allowed to store a small amount of 
data in a cookie file (e.g., date & time of visit, items purchased)
◼ when the user returns to that site, the Web server can retrieve any cookies it 
previously stored
◼ NOTE: only the site that stored the cookie is able to retrieve it
cookies can improve the user's experience, but can also be intrusive
◼ most browsers enable the user to control the use of cookies
13


key: chroma:document
string_value:
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)
1


key: chroma:document
string_value:
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 associate JavaScript statements with certain HTML elements so that they 
react to actions taken by the user (e.g., a button click)
2


key: chroma:document
string_value:
ID Attributes
in order for an element to behave dynamically, it must have an ID attribute 
◼ ID is assigned a unique identifier by which that element can be accessed and 
changed
<img id="familyImg" src="Images/beach.jpg" alt="My Family">
an identifier should start with a lowercase letter, consist of letters and digits 
 e.g., familyImg      mysteryImg      outputSpan      num1Box
once an element has an ID, it can be accessed and altered using dynamic 
attributes known as event handlers
◼ the ONMOUSEOVER attribute specifies the action(s) to take place when the 
mouse is moved over the element
◼ the ONMOUSEOUT attribute specifies specifies the action(s) to take place when 
the mouse is moved off the element
◼ the actions are encoded as statements in the JavaScript language
3


key: chroma:document
string_value:
Event Handler Attributes
for example, can have an image that reacts to mouse movements:
<img src="ADDRESS_OF_IMAGE" alt="DESCRIPTIVE_TEXT"
     onmouseover="CODE_TO_EXECUTE_WHEN_MOUSE_GOES_OVER_IMAGE"
     onmouseout="CODE_TO_EXECUTE_WHEN_MOUSE_LEAVES_IMAGE">
the simplest type of action is changing the value of an element's attribute
◼ this is accomplished via a JavaScript assignment statement
ELEMENT_ID.ATTRIBUTE_NAME = NEW_ATTRIBUTE_VALUE;
for example, the following JavaScript assignment will change the SRC 
attribute of the element with ID mysteryImg 
mysteryImg.src='http://compsciconcepts.com/Images/happy.gif';
4


key: chroma:document
string_value:
Mystery Image Page
▪ initially, the 
image displays 
a '?'
▪ when mouse 
moves over, 
SRC attribute 
is assigned to 
happy face
▪ when mouse 
leaves, SRC 
attribute is 
assigned back 
to '?'
5


key: chroma:document
string_value:
Strings & Syntax Errors
a string literal (or just string) is a sequence of characters enclosed in quotes
◼ to avoid confusion, we will always use double quotes for HTML strings; single 
quotes for JavaScript strings
<img id="mysteryImg" src="mystery.gif" alt="Mystery image"
     onmouseover="mysteryImg.src='happy.gif';"
     onmouseout="mysteryImg.src='mystery.gif';">
syntax errors are errors in the format of HTML or JavaScript statements
◼ for example, misspelling an element ID in a JavaScript assignment:
 mysteryimg.src='http://compsciconcepts.com/Images/happy.gif';
unlike HTML syntax errors (which are largely ignored by the browser, 
JavaScript syntax errors often just fail
◼ browsers produce error messages that help to identify JavaScript errors
◼ in Google Chrome, error messages appear in the JavaScript Console:
View menu → Developer → JavaScript Console 
◼ when a page fails to behave as expected, CHECK THE ERROR MESSAGES!
6


key: chroma:document
string_value:
Multiple Actions
JavaScript assignments can similarly change other element attributes
e.g., can change an images height:  mysteryImg.height = 200;
if desired, an event handler can perform multiple actions (separated by ;)
◼ in this example, both the SRC and HEIGHT change on mouse events
7


key: chroma:document
string_value:
Interaction via Buttons
a button is an HTML element that appears as a labeled rectangle or oval
◼ usually associated with the ONCLICK event handler attribute, which specifies the 
action to take place when the button is clicked
general form:
<button onclick="CODE_TO_BE_EXECUTED_WHEN_MOUSE_CLICKS_ON_BUTTON">
  BUTTON_LABEL
</button>
typically, buttons are used to initiate actions on other elements
▪ e.g., click on a button to change the src or height/width of an img
<button onclick="mysteryImg.height=200;">Expand the Image</button>
8


key: chroma:document
string_value:
Button Example
image initially 
displays a 
question mark
when Show 
Image button 
is clicked, the 
image changes 
to 
when Hide 
Image button 
is clicked, it 
changes back 
to ? 
9


key: chroma:document
string_value:
Dynamic Text
to display text within a page, there are 2 main options
1. alert statement: will display a simple text message in a separate alert window
2. innerHTML attribute: can display text directly in the page
general form of an alert statement: alert('MESSAGE'); 
◼ when executed, it opens a separate window displaying that message
<button onclick="alert('Yeah, right.');"> 
  Click for free money!
</button>
◼ alert statements are useful when you want to display a short (1-line) message
◼ the messages are limited, in that they can't include any HTML tags
◼ can be annoying to the user since the pop-up window must be manually closed
note: if a message contains an apostrophe, must use backslash (escape character) to 
distinguish it from the ending quote:  alert('I\'m happy you are here.');
10


key: chroma:document
string_value:
Help Page
when the mouse clicks on 
the image, an alert 
window is opened,
displaying the message
note: the user must click 
OK to close the window
11


key: chroma:document
string_value:
innerHTML
better yet, embed the text directly in the page
text-based elements (p, span, div) have an innerHTML attribute
◼ can be used to access or change the text within that element
◼ be careful: the capitalization must be exact
 outputSpan.innerHTML = 'Hello';
 outputDiv.innerHTML = 
   '<p>You can write long messages that are embedded directly ' +
   'in the page. You can even add <i>HTML formatting</i> to the ' +
   'text. </p> <p>The contents of this dynamic DIV element is ' +
   'being assigned multiple paragraphs.</p>';
 outputP.innerHTML = outputP.innerHTML + '!';
12


key: chroma:document
string_value:
Help Page
initially, outputSpan is blank
when the mouse moves over 
the image, a text message is 
assigned to 
outputSpan.innerHTML 
(showing the message)
when the mouse moves off 
the image, an empty string is 
assigned back to 
outputSpan.innerHTML
(erasing the message)
13


key: chroma:document
string_value:
Common Errors
two types of errors are common when displaying complex messages
BROKEN STRING: can't start a string on one line and continue on the next 
 alert('This example is illegal because the 
                string is broken across lines');
 alert('This example is OK because the message ' + 
           'is broken into two distinct strings'); 
DISCONNECTED STRING: if message is broken into pieces, must have + 
between the pieces to connect them
 alert('This example is illegal because '
                   'there is not a plus connecting the pieces');
 alert('This example is OK because the ' +
                   'pieces are properly connected');
error messages in the JavaScript Console make identifying these types of 
mistakes much easier 14


key: chroma:document
string_value:
Dynamic Style
it is also possible to change the style attribute of an element
◼ must specify the property to be changed:  style.PROPERTY
◼ if the property contains a hyphen, instead use capitalization
e.g., background-color → backgroundColor
<p id="colorP"
   onmouseover="colorP.style.color='red';" 
   onmouseout="colorP.style.color='black';">
    This text will turn red when the mouse moves over it.
</p>
<p>This is a really 
   <span id="colorSpan
         onmouseover="colorSpan.style.backgroundColor='yellow';"
         onmouseout="colorSpan.style.backgroundColor='white';">
     important</span> point to note.
</p>
15


key: chroma:document
string_value:
Machine Learning
Machine Learning (ML) is driving many powerful applications
◼ ML utilizes algorithms to process (potentially large) data sets to improve 
problem solving
◼ historically, has been seen as a subdiscipline of Artificial Intelligence
◼ the new discipline Data Science utilizes ML to process (potentially large) 
data sets to discover patterns
◼ this process is known as Data Mining
Machine Learning relies heavily on supervised learning
◼ algorithms are trained by providing sample inputs and classifications
◼ the algorithms learn to recognize patterns and classify new inputs
1


key: chroma:document
string_value:
Example: OCR
Optical Character Recognition is used by devices (e.g., phones, 
tablets, scanners) to extract text from images
◼ when scanning printed text, each font has slight variations
◼ handwriting can have extreme variations
◼ programming every variation would be impossible
◼ instead, provide numerous examples and have the program learn to identify
 essentially, the program deduces which features are essential to each character
 uses those features to classify new examples
2


key: chroma:document
string_value:
similarly, facial recognition software identifies facial features (e.g., 
distance between eyes, ear size)
◼ can then match those features against new images to identify people
◼ since many features persist regardless of lighting or perspective, can be effective 
under varying conditions
◼ many smartphones utilize facial recognition for security
◼ has been used by law enforcement, but false matches and biases have caused 
many to rethink
Example: facial recognition
3


key: chroma:document
string_value:
autonomous vehicles utilize cameras, radar, lidar (light detection) 
and even GPS sense their surroundings
◼ they are programmed to react under specific circumstance, but learn to apply 
rules to new situations
◼ they can improve over time as new circumstances are experienced
◼ July-Oct 2022, 605 reported crashes by advanced driver assistance vehicles
Example: self-driving cars
4


key: chroma:document
string_value:
ChatGPT (Chat Generative Pre-trained Transformer) was released in 
Nov 2022 by OpenAI
◼ was trained by providing recorded conversations and also utilized human trainers 
to provide feedback
◼ in addition to carry on on a conversation, can write code, music, poems, …
Example: chatbots
5
how will tools like this change 
• education 
• writing 
• software development
• tech support
• therapy


key: chroma:document
string_value:
Example: data mining
6
it was estimated that 
1.1 trillion MB of data 
was generated every 
day in 2021
Data Science is a 
discipline that focuses 
on extracting patterns 
and trends from data
◼ relies on Machine 
Learning to process the 
massive amounts of 
data and learn what 
features are significant


key: chroma:document
string_value:
Neural Networks
at the core of most Machine Learning algorithms are neural networks
◼ a neural network mimics the structure of the human brain
◼ utilizes supervised learning to develop proficiency in recognizing patterns
neural nets predate modern computers
◼ first invented by McCulloch and Pitts in 1943
7
general brain architecture:
many (relatively) slow neurons, 
interconnected
dendrites serve as input devices 
(receive electrical impulses from 
other neurons)
cell body "sums" inputs from the 
dendrites (possibly inhibiting or 
exciting)
if sum exceeds some threshold, 
the neuron fires an output 
impulse along axon


key: chroma:document
string_value:
Artificial Neurons
McCulloch & Pitts (1943) described an artificial neuron 
◼ inputs are binary: 0 (no input signal) or 1 (input signal)
◼ each input has a weight associated with it
◼ the activation function multiplies each input value by its weight
◼ if the sum of the weighted inputs >= , 
then the neuron fires (outputs 1), else doesn't fire (outputs 0)
8
neural networks are based on the brain metaphor
large number of simple, neuron-like processing elements
large number of weighted connections between neurons
note: the weights encode information, not symbols!
parallel, distributed control
emphasis on learning
if wixi >= , output = 1
if wixi < ,   output = 0

x1 xnx2
. . .
w1
w2
wn


key: chroma:document
string_value:
Computation via Neurons
can view an (artificial or not) neuron as a computational element
◼ accepts or classifies an input if the output fires
9
INPUT:  x1 = 1, x2 = 1
.75*1 + .75*1 = 1.5 >= 1  ➔ OUTPUT: 1
INPUT:  x1 = 1, x2 = 0
.75*1 + .75*0 = .75 < 1  ➔ OUTPUT: 0
INPUT:  x1 = 0, x2 = 1
.75*0 + .75*1 = .75 < 1  ➔ OUTPUT: 0
INPUT:  x1 = 0, x2 = 0
.75*0 + .75*0 = 0 < 1 ➔ OUTPUT: 0

x1 x2
.75 .75
this neuron computes the AND function


key: chroma:document
string_value:
Learning Algorithm
Rosenblatt (1958) devised a learning algorithm for artificial neurons
◼ start with a training set (example inputs & corresponding desired outputs)
◼ train the network to recognize the examples in the training set (by adjusting the 
weights on the connections)
◼ once trained, the network can be applied to new examples
this basic algorithm has been expanded to handle complex applications 
10
e.g., OCR
◼ inputs are pixels in a scanned image
◼ a "hidden" layer identifies relevant 
features (e.g., horizontal line near top, 
diagonal in middle)
◼ the combination of features discovered 
by the hidden layer identifies the 
character


key: chroma:document
string_value:
11
Generalization problem
there is always a danger that the network will focus on specific 
(maybe unintentional) features as opposed to general patterns
 to avoid networks that are too specific, cross-validation can be used 
1. split training set into training & validation data
2. after each generation, test the net on the validation data
3. continue until performance on the validation data diminishes
1 1 1 1
2 2 2 2
suppose a network is trained to recognize digits:
▪ training set for 1:
▪ training set for 2:
2
when the network is asked to identify             it comes back with 1.  WHY?


key: chroma:document
string_value:
Neural Net Applications
Aerospace: Aircraft component fault detectors and simulations, aircraft control systems
Automotive: Improved guidance systems, virtual sensors, warranty activity analyzers
Electronics: Chip failure analysis, circuit chip layouts, machine vision, non-linear modeling, process control
Manufacturing: Machine diagnosis, product design and analysis, visual quality inspection systems
Robotics: Forklift robots, manipulator controllers, trajectory control, and vision systems
Telecommunications: Network monitoring, speech recognition, customer payment processing systems
Banking: Credit card attrition, credit and loan application evaluation, fraud and risk evaluation
Business Analytics: Customer behavior modeling, fraud propensity, market research
Financial: Corporate financial analysis, currency price prediction, loan advising, portfolio trading
Securities: Automatic bond rating, market analysis, and stock trading advisory systems


key: chroma:document
string_value:
Financial: Corporate financial analysis, currency price prediction, loan advising, portfolio trading
Securities: Automatic bond rating, market analysis, and stock trading advisory systems
source: https://www.smartsheet.com/neural-network-applications
12
more than 9,000 companies (including credit cards) use FICO Falcon
◼ uses neural nets to model customer behavior, identify fraud
◼ claims improvement in credit card fraud detection of 30-70%


key: chroma:document
string_value:
NN example
suppose we wanted to provide guidance on major selection
◼ hypothesis: certain personality traits or life skills suggest certain majors
◼ conduct a survey of students, asking them to self-assess their traits/skills on a 
scale of 0 to 1.0, along with their major
◼ build a network of artificial neurons, with three inputs (corresponding to survey 
skills) and a single output (corresponding to major)
How 
creative 
are you?
Good at 
problem 
solving?
How 
extraverted 
are you?
Major
stu1 0.85 0.75 0.9 GDE (0)
stu2 0.9 0.7 1.0 GDE (0)
stu3 0.8 0.9 0.6 GDE (0)
stu4 0.2 0.9 0.2 CSC (1)
stu5 0.6 0.8 0.4 CSC (1)
stu6 0.8 0.8 0.8 CSC (1)
13


key: chroma:document
string_value:
NN example
◼ feed those inputs and outputs to the network and train it to recognize
◼ once trained, it can be applied to new patterns to classify them (based on best fit)
note: this is a very small, non -scientific example
▪ data scientists typically deal with massive amounts of data (e.g., hundreds or 
thousands of survey responses)
▪ utilize analytical methods to ensure statistical significance
14
How 
creative 
are you?
Good at 
problem 
solving?
How 
extraverted 
are you?
Major
stu1 0.85 0.75 0.9 GDE (0)
stu2 0.9 0.7 1.0 GDE (0)
stu3 0.8 0.9 0.6 GDE (0)
stu4 0.2 0.9 0.2 CSC (1)
stu5 0.6 0.8 0.4 CSC (1)
stu6 0.8 0.8 0.8 CSC (1)


key: chroma:document
string_value:
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
1


key: chroma:document
string_value:
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
◼ Ada Lovelace developed instructions for the never-quite-finished 
Analytical Engine – is considered the world's first programmer
 2


key: chroma:document
string_value:
Generation 0 (cont.)
1930's – several engineers independently built 
"computers" using electromagnetic relays
◼ an electromagnetic relay is physical switch, which can 
be opened/closed via electrical current 
◼ relays were used extensively in early telephone 
exchanges 
◼ 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
 
3


key: chroma:document
string_value:
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)
◼ 18,000 vacuum tubes and 1,500 relays
◼ weighed 30 tons, consumed 140 kwatts
◼ "programmed" by women CS pioneers
4


key: chroma:document
string_value:
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 00101110
5


key: chroma:document
string_value:
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
as the cost of computers dropped, high -level languages were designed 
to make programming more natural (& efficient)
 FORTRAN (1957, Backus at IBM)
PROGRAM add
READ *, a,b
s = a + b
PRINT *, ' The sum is ', s
STOP
END
 LISP (1959, McCarthy at MIT)
 COBOL (1960, Hopper at DOD)
6


key: chroma:document
string_value:
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)
◼ was made possible by miniaturization & improved manufacturing
◼ allowed for mass-producing useful circuitry
1960's saw the rise of computing for business
 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
◼ specialized programming languages were developed, e.g., 
Pascal (1971, Wirth),  C (1972, Ritchie)
7
U.S. space program was a driving force behind innovation
◼ computers began to replace humans for complex 
calculations (e.g., Katherine Johnson)
◼ Margaret Hamilton at MIT led team that developed Apollo 
Guidance system


key: chroma:document
string_value:
Generation 4: Microprocessors
1971 – Intel marketed the first microprocessor, the 
4004, a chip with all the circuitry for a calculator
◼ by the late 1970's, manufacturing advances allowed 
for the very large scale integration (VLSI) of 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
◼ Moore's Law (more of an observation, really)– 
the number of transistors that could fit on a chip 
doubled every 1-2 years
8


key: chroma:document
string_value:
Generation 4: Microprocessors
with microprocessors came personal computing
◼ 1975 - Bill Gates & Paul Allen founded Microsoft 
Gates wrote a BASIC interpreter for the first PC (Altair)
◼ 1977 - Steve Wozniak & Steve Jobs founded Apple 
went from Jobs' garage to $120 million in sales by 1980
◼ 1980 - IBM introduced PC 
Microsoft licensed the DOS operating system to IBM
◼ 1984 - Apple countered with Macintosh 
introduced the modern GUI-based OS (which was mostly 
developed at Xerox)
◼ 1985 - Microsoft countered with Windows 
in the 1980's
◼ demand grew for networking computers together
1982: 235 computers connected to ARPANet
1989: 300,000 computers connected to Internet
◼ object-oriented programming represented a new 
approach to program design which views a program 
as a collection of interacting software objects that 
model real-world entities
 9


key: chroma:document
string_value:
Generation 5: ULSI
the latest generation of computers is still hotly debated
◼ no new switching technologies, ultra large scale integration (ULSI) has changed 
how computers are used
1n 1989, the Intel 486 contained 1.2 million transistors
◼ manufacturing improvements are more difficult to achieve as components get 
smaller and smaller (Moore's Law in jeopardy?)
workarounds
▪ multi-core processors increase the 
chip size by adding duplicate circuitry 
so that it can execute operations 
simultaneously
▪ parallel processing computers have 
multiple independent processors that 
can share the load (e.g., a Web 
server)
10


key: chroma:document
string_value:
Generation 5: ULSI (cont.)
Wi-fi and wireless broadband have made computing mobile and pervasive
◼ wi-fi utilizes radio waves over short distances to connect computers and devices
◼ typical speed & range: 100-200 Mbits/sec, 150-300 feet
1. user enters commands on computer/device
2. command is translated into radio signal, broadcast to wi-fi router
3. router carries out the command via Internet connection
4. response is translated into radio signal, broadcast back to computer/device
◼ a longer range alternative to wi-fi is cellular networking 
◼ 4G (15-25 Mbits/sec) & now 5G (50 Mbits/sec – 1 Gbits/sec), nationwide coverage
11
Artificial Intelligence (AI) applications dominate the news
◼ Apple's Siri (2011) and Amazon's Alexa (2014) can recognize voice commands 
and control smart home devices
◼ facial recognition software is used by law enforcement and businesses
◼ credit card companies model purchasing patterns to identify fraud


key: chroma:document
string_value:
and control smart home devices
◼ facial recognition software is used by law enforcement and businesses
◼ credit card companies model purchasing patterns to identify fraud
◼ retailers like Amazon use your history to predict future purchases
◼ Self-driving cars from Uber and Tesla use video processing and AI techniques 
to control vehicles on open roads


key: chroma:document
string_value:
Speed matters
ENIAC (1946)
◼ could perform 385 operations per 
second
12
75 years later…
iPhone 13 (2021) 
◼ can perform 15.8 trillion operations per 
second
◼ 41 billion times faster!
it would take the ENIAC 1,301 years to do what your 
iPhone can do in 1 second


key: chroma:document
string_value:
Speed REALLY matters
ENIAC (1946)
◼ could perform 385 operations per 
second
13
Fugaku supercomputer (2021)
◼ can perform 442 quadrillion operations 
per second
◼ 1.1 quadrillion times faster!!!
it would take the ENIAC 36.4 million years to do 
what the Fugaku can do in 1 second


key: chroma:document
string_value:
Computing entrepreneurs
Richest People in the World
(Forbes, 3/5/21)
1. Jeff Bezos $177.0 billion Age: 57
2. Elon Musk $151.0 billion Age: 50
3. Bernard Arnault $150.0 billion Age: 72
4. Bill Gates $124.0 billion Age: 65
5. Mark Zuckerberg $97.0 billion Age: 36
6. Warren Buffet $96.0 billion Age: 90
7.  Larry Ellison $93.0 billion Age: 76
8. Larry Page $91.5 billion Age: 47
9. Sergey Brin $89.0 billion Age: 47
10. Mukesh Ambani $84.5 billion Age: 63
…
14. Steve Ballmer $68.7 billion Age: 64
15. Ma Huatang $65.8 billion Age: 49
14


key: chroma:document
string_value:
Text Boxes
HTML event handlers enable the user to interact with the page
e.g., move the mouse over an image to change it 
e.g., click on a button to display a text message in a page division 
for greater control, the user must be able to enter information into the page
e.g., enter words to complete a fill-in-the-blank story
e.g., enter grades to calculate a course average
a text box is an HTML element that is embedded in the page
     <input type="text" id="BOX_ID" size=NUM_CHARS value="INITIAL_CONTENTS">
▪ the user can enter text directly in the box
▪ a JavaScript statement can then access the contents of the text box by accessing 
its VALUE attribute
BOX_ID.value
1


key: chroma:document
string_value:
Greetings Page (v.1)
"Jody" is the default 
value
when button is 
clicked, an alert 
window displays 'Hi 
Jody'
the user can enter 
his/her name in the 
text box
note: userBox.value does not 
have quotes around it
what would happen if it did?
2


key: chroma:document
string_value:
Greetings Page (v.2)
alternatively, could 
display the greeting 
in a dynamic 
paragraph
initially, outputP is 
empty
when button is 
clicked, the greeting 
is assigned to its 
INNERHTML attribute
3


key: chroma:document
string_value:
Form Letter Example
note: each box must have a unique ID
this page has 3 text 
boxes, uses 
contents to generate 
a custom form letter
4


key: chroma:document
string_value:
Simplifying Pages
we should be able to glance at the body of a page and visualize its contents
◼ consider the body of the form generator page
◼ the onclick code has nothing to do with the look of the page but its size and 
complexity clutter the body
5


key: chroma:document
string_value:
User-defined Functions
can simplify the body by moving the JavaScript statements to the head
◼ define a function that encapsulates those statements; then call from onclick
mathematically speaking, a function is a mapping from inputs to an output
9 → 3  |-2| → 2  max(5, 2) → 5
to a developer, a function is a unit of computational abstraction
◼ a function encapsulates statement(s) under a name; to execute, only need to know 
the name (i.e., call the function)
function definition:   function call:
function FUNCTION_NAME() {
    STATEMENTS_TO_BE_EXECUTED    FUNCTION_NAME();
}
◼ function definitions are place in the head of a page, in a script element 6


key: chroma:document
string_value:
Function Example
this page behaves 
the same as 
form1.html
the action of the 
button is 
encapsulated in the 
GenerateLetter 
function in the HEAD 
(in SCRIPT tags)
the BODY is 
simplified, since the 
ONCLICK just 
contains a call to the 
function
7


key: chroma:document
string_value:
Another Example
Animal Gallery: contains 
▪ image of an animal
▪ a text box where the user can enter 
an animal name
▪ a button for changing the image
note how simple 
the BODY is 8


key: chroma:document
string_value:
Another Example
each button has its own 
corresponding function
when clicked, the function 
is called to display a 
quotation in the page
note how simple 
the BODY is
9


key: chroma:document
string_value:
Design Guidelines
✓ be conservative in your use of color
✓ be consistent in your use of formatting
✓ avoid overriding the browser defaults unless it is necessary
✓ don't center paragraphs
✓ label interactive elements (buttons, text boxes) clearly
✓ document the source code in case anyone views it
include a comment block at top with your name, file name, and brief description
✓ use descriptive id names
convention: descriptor + elementType, e.g., vacationImg, outputP
✓ when defining a complex action, place in function definition in the head 
and call the function from the event handler
10


key: chroma:document
string_value:
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
1. 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
 CHECK THE JAVASCRIPT CONSOLE FOR ERROR MESSAGES!
2. 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, division by zero produces Infinity)
 AGAIN, CHECK THE JAVASCRIPT CONSOLE!
1. 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


key: chroma:document
string_value:
 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 logic errors: diagnostic alert statements
◼ at various intervals in the code, display the values of key variables using alert
◼ you can then isolate at what point the program is going wrong
11


key: chroma:document
string_value:
Early science
science: a system of knowledge covering general truths or the operation of 
general laws especially as obtained and tested through scientific method 
(Merriam-Webster dictionary)
modern science traces its roots back to the Greek 
natural philosophers 
◼ Thales (6 c B.C.) was first to break from mythology
 observed and devised theories about nature 
◼ Plato (4 c B.C.) proposed a grand theory of cosmology
 claimed heavenly bodies move uniformly in circles, because 
of their divine, geometric perfection 
 believed observation was confused and impure, truth was 
found through contemplation
◼ Aristotle (4 c B.C.) proposed a common-sense vision of 
the natural world that stood for 2,000 years
 studied and wrote on a cosmology, physics, biology, 
anatomy, logic, …
 placed greater emphasis on observation than Plato, but still 
not experimental
Greek natural philosophy is "pre-scientific", since it relied on 
contemplation/observation, but not experimentation


key: chroma:document
string_value:
 placed greater emphasis on observation than Plato, but still 
not experimental
Greek natural philosophy is "pre-scientific", since it relied on 
contemplation/observation, but not experimentation
science is important in our daily lives because:
◼ it advances our understanding of the world and our place in it
◼ scientific advances can lead to practical applications (e.g., technology, medicine, …)
1


key: chroma:document
string_value:
Roman times → Middle Ages
Roman civilization built upon the tradition of Greek natural philosophy
◼ the Romans are better known for engineering than theoretical science  
◼ Pliny (1 c.) categorized plants, animals and minerals
◼ Galen (2nd century) studied human anatomy and physiology
the fall of Rome (in 476) led to a discontinuity in western civilization
◼ in western Europe, population dropped, literacy virtually disappeared, and Greek 
knowledge was lost
◼ in eastern Europe, Greek knowledge was suppressed by orthodox Christianity in 
the Byzantine Empire (which finally fell in 1453)
during Europe's "Dark Age," medieval Islam became the 
principal heir to Greek science
◼ in the 7th-14th centuries, the Islamic Empire covered 
parts of Europe, northern Africa, the Middle East, and 
western Asia
◼ Greek writings were preserved and advanced by Arab 
scholars
◼ the term "algorithm" is named after Persian scholar 
Muhammad ibn Musa al-Khwarismi 2


key: chroma:document
string_value:
Scientific Revolution
the Renaissance (15th-16th centuries) was instigated by the 
rediscovery of Greek science
◼ Greek knowledge was rediscovered by Crusaders to the Middle East; 
retrieved from medieval monasteries
◼ Leonardo da Vinci (1452-1519) was artist, astronomer, geometer, 
engineer, …
◼ Gutenberg's printing press made the broad dissemination of 
knowledge possible
the Scientific Revolution (16th -17th centuries) was brought about 
by a period of intellectual upheaval in Europe
◼ the Protestant Reformation, new world exploration, …
◼ the cultural environment allowed for questioning religious and 
scientific dogma – the universe was viewed as a complex machine 
that could be understood through observation and experimentation
◼ Copernicus proposed a sun-centered cosmology (1543)
 Kepler refined the heliocentric model, using elliptical orbits (1609)
◼ Galileo pioneered the use of experimentation to validate observational 
theories


key: chroma:document
string_value:
 Kepler refined the heliocentric model, using elliptical orbits (1609)
◼ Galileo pioneered the use of experimentation to validate observational 
theories
 father of modern science (as well as modern physics and astronomy)
◼ Newton described universal gravitation, laws of motion (1687) 3


key: chroma:document
string_value:
Modern Science
the Scientific Revolution established science as the preeminent source for 
the growth of knowledge
◼ biology: Pasteur, Watson & Crick, …
◼ chemistry: Dalton, Mendeleev, Curie, …
◼ physics: Maxwell, Curie, Einstein, …
4
the scientific method provides the common 
process by which modern science is conducted
1. Observe a phenomenon
2. Hypothesize how it works
3. Design an experiment to test it
4. Experiment to confirm/deny
5. Analyze the results
6. Revise or refine the hypothesis
generally, the process repeats since the results may 
lead to revisions to the hypothesis or experiment


key: chroma:document
string_value:
Scientific Method
EXAMPLE: understanding planetary motion
1. Observe that some lights in the night sky move different, faster than others.
2. Hypothesize that those lights (planets) are closer to the earth.
3. Develop a model of motion (say, Copernicus' circular orbits around the sun).
4. Conduct the experiment to see telescopic observations match the model.
5. Analyze the results and see that the observations are close but not exact – 
revise the model to use Kepler's elliptical orbits and repeat.
5
the scientific method can be applied to real -world situations as well
◼ EXAMPLE: an auto mechanic observes a misfiring engine, hypothesizes that the cause 
is a bad spark plug and designs an experiment (replace it) to test
◼ EXAMPLE: a programmer observes a program that doesn't work, hypothesizes the 
cause if a malformed statement and designs an experiment (bug fix) to test
reproducibility is essential to the scientific method


key: chroma:document
string_value:
cause if a malformed statement and designs an experiment (bug fix) to test
reproducibility is essential to the scientific method
◼ the same experiment, under the same conditions, should produce the same result
◼ if a scientific discovery is not reproducible, it will not be accepted
consistency is a measure of how close the results are each time you conduct the experiment
accuracy is a measure of how close the results are to the correct (or expected) value


key: chroma:document
string_value:
Computational Thinking
the scientific method is designed for understanding a phenomenon
◼ may not be directly applicable to real-world problems solving
computational thinking is a problem-solving approach that involves 
expressing problems and their solutions in ways that a computer could 
execute 
◼ first coined by Papert in 1980, made popular by Jeannette Wing in 2006
◼ computational thinking has been recognized by many as an essential 21st century 
skill (along with critical thinking, communication, collaboration, and creativity)
6
high-level characteristics of computational thinking
◼ DECOMPOSITION – breaking a large, complex problem into smaller, more 
manageable problems
◼ PATTERN MATCHING – recognizing how solutions to similar problems can be applied 
to new problems 
◼ ABSTRACTION – focusing on important details while ignoring irrelevant information
◼ ALGORITHMS – designing and implementing the solution in the form of an algorithm
real-world example: assembling a bookcase


key: chroma:document
string_value:
CT Example
consider the task of finding the oldest person in a room
◼ there are a number of issues to consider, different approaches you could take
DECOMPOSITION
 tasks that will need to be performed:
✓ systematically process each person
✓ be able to determine a person's age
✓ record the names/ages so that will know the oldest at the end
 
PATTERN MATCHING
 learn from past experiences that were similar
✓ lining the people up will make it easier to cover everyone
✓ pencil & paper are effective for simple tasks like these
ABSTRACTION
 there are a lot of characteristics we don't care about (hair color, middle initial)
✓ if born on the same day, we will consider the same age
✓ if more than one "oldest" person, any one will do
ALGORITHMS
 can now devise an algorithm, step-by-step sequence of instructions, to solve this
7


key: chroma:document
string_value:
Algorithm 1
Finding the oldest person (algorithm 1)
1. line up all the people along one wall
2. ask the first person to state his or her name and birthday, then write this 
information down on a piece of paper
3. for each successive person in line:
i. ask the person for his or her name and birthday
ii. 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
8


key: chroma:document
string_value:
Algorithm 1 Analysis
9
algorithm 1 works, since the oldest person will eventually be found & recorded
◼ 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
for example, assume it takes 10 seconds to compare birthdays
 8 people → 10*8 = 80 seconds (1.33 minutes)
 16 people → 10*16 = 160 seconds (2.67 minutes)
 32 people → 10*32 = 320 seconds (5.33 minutes)
 . . .
 100 people → 10*100 = 1,000 seconds (16.67 minutes)
 . . .
 400 people → 10*400 = 4,000 seconds (1 hour & 6.67 minutes)
this algorithm works, but it does not scale well if the number of people gets big
◼ consider a more complex but also more efficient algorithm


key: chroma:document
string_value:
Algorithm 2
Finding the oldest person (algorithm 2)
1. line up all the people along one wall
2. as long as there is more than one person in the line, repeatedly
i. 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
ii. ask each pair of people to compare their birthdays
iii. request that the younger of the two leave the line
when there is only one person left in line, that person is the oldest
10


key: chroma:document
string_value:
Algorithm 2 Analysis
11
algorithm 2 works, since the oldest person in a pair never sits and the process 
eventually reduces down to that oldest person
◼ 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 (since all pair comparisons in a round 
take place simultaneously)
 the number of rounds is the number of times the people can repeatedly be 
divided in half (mathematically speaking, the log2 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
for example, assume it takes 10 seconds to compare birthdays
 8 people → 10* log2 8 = 10*3 = 30 seconds (0.5 minutes)
 16 people → 10* log2 16 = 10*4 = 40 seconds (0.67 minutes)
 32 people → 10 * log2 32 = 10*5 = 50 seconds (0.83 minutes)
 . . .
 100 people → 10 * log2 100 = 10*7 = 70 seconds (1.16 minutes)
 . . .


key: chroma:document
string_value:
 32 people → 10 * log2 32 = 10*5 = 50 seconds (0.83 minutes)
 . . .
 100 people → 10 * log2 100 = 10*7 = 70 seconds (1.16 minutes)
 . . .
 400 people → 10 * log2 400 = 10*9 = 90 seconds (1.5 minutes)


key: chroma:document
string_value:
Multiple Solutions
many real-world problems can be solved in multiple ways
◼ when presented with this problem, most people would devise a solution similar to 
Algorithm 1 (with many different variations possible)
 it is simple to describe and understand
 it is reasonably fast for small numbers of people
◼ developing Algorithm 2 requires considerable experience solving similar problems
 must be able to ABSRACT the relevant features of this problem, PATTERN MATCH with 
past solutions to similar problems, and DECOMPOSE the solution to fit this new problem.
like most endeavors, the more computational thinking you do, they better you 
become at it
12
# of people time for Algorithm 1 time for Algorithm 2
8 80 sec 30 sec
16 160 sec 40 sec
32 320 sec 50 sec
…
100 1,000 sec 70 sec
…
400 4,000 sec 90 sec


key: chroma:document
string_value:
Data Types
each unit of information processed by a computer belongs to a general 
category or data type
◼ JavaScript has three predefined data types
1. string for representing text values (e.g., 'abcd', 'two words')
2. number for representing numeric values (e.g. 12, 3.99)
3. Boolean for representing logical values (trueor false)  LATER
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 (/)
text boxes allow the user to enter strings and access those entries
◼ there is an equivalent element for numbers: number box
1


key: chroma:document
string_value:
Number Box
a number box is an input element (similar to text box)
▪ type attribute is assigned "number" (instead of "text")
▪ optional value attribute is same as for text box – specifies 
default value that appears in the box
▪ instead of size attribute, number boxes specify min and max 
values – the size is adjusted to fit that range
<input type="number" id="numBox" min=0 max=100 value=50>
2
to access the number in a number box, use valueAsNumber attribute
 numBox.valueAsNumber


key: chroma:document
string_value:
Tip Calculator
here, the user enters a check 
amount and tip percentage 
(default is 15%)
when button is clicked, 
accesses those numbers, 
calculates & displays tip
3


key: chroma:document
string_value:
valueAsNumber vs. value
similar to text boxes, number boxes have a value attribute
▪ the value attribute always returns the contents of the box as a string
▪ this is NOT what you normally want when accessing a number box
 e.g., suppose the user enters 12 in a number box named numBox
numBox.value  evaluates to '12'
(numBox.value + 1) evaluates to '121'  ???
recall, when + is applied to 2 numbers, addition:     1 + 2 = 3
 when + is applied to 2 strings, concatenation:    'a' + 'b' = 'ab'
 when + is applied to a string and a number, it converts the number to a 
     string and concatenates:      '12' + 1 = '12' + '1' = '121'
BE CAREFUL TO ALWAYS USE valueAsNumber TO ACCESS NUMBER BOX CONTENTS
4


key: chroma:document
string_value:
Variables
a variable is a name used to symbolize a dynamic (changeable) value
▪ as before, assign a value using '=':  
VARIABLE = VALUE;
variables are commonly used to simplify code by:
1. storing number values from boxes
amount = amountBox.valueAsNumber;
percent = percentBox.valueAsNumber;
2. or, storing the results of computations
tip =  amount * (percent/100); 
5


key: chroma:document
string_value:
Tip Calculator
code is simplified by use of 
variables
tip.toFixed(2) rounds the tip  
to 2 decimal places
6


key: chroma:document
string_value:
Variable Names
a variable name should start with a lowercase letter, consist of letters & digits
◼ a variable name should be chosen to be descriptive of its purpose
◼ e.g., mysteryImg, outputSpan
7


key: chroma:document
string_value:
Variables & Assignments
variables can be assigned various types of values, including numbers and 
mathematical expressions
▪ each variable has a memory cell associated with it, where a value can be stored
▪ when an expression appears on the right-hand side, it is evaluated and the result is 
assigned to the variable (i.e., stored in its memory cell)
▪ when a variable appears in an expression, its value (i.e., the value stored in its 
memory cell) is accessed and substituted into the expression
reminder: '=' is not the equality operator
to avoid confusion: read '=' as 'gets', as in   ' y gets y-1' 8


key: chroma:document
string_value:
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 → 1000000000000000000000000 
◼ 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-323 . . . 1e309, 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.., 0.9999999999999999 can be represented exactly
  0.99999999999999999 is rounded up to 1
9


key: chroma:document
string_value:
Patterns & Spacing
note the spacing in the Calculate function
◼ blank lines are ignored by the browser, but are helpful to a developer
◼ here, there are three main tasks
1. get the (numeric) contents of the text boxes
2. perform a computation on those numbers
3. display the result of the computation in the page
◼ inserting blank lines to separate these tasks makes the code easier to 
understand
 similar to dividing an essay into paragraphs
◼ be aware: this same pattern will reappear in many pages
10


key: chroma:document
string_value:
Predefined Functions
in JavaScript, a function is applied to inputs via a function call
 num = Math.sqrt(25);
here, Math.sqrt is being called with input 25; it returns the output 5
11


key: chroma:document
string_value:
functest
the functest.html page is provided for you to explore the different math 
functions
◼ select the function from a pull-down menu & inter the input(s) in text box(es)
◼ click the button to see the function call and its output
12


key: chroma:document
string_value:
Point Distance
user enters two points (x1, y1) 
and (x2, y2) in text boxes
when button is clicked, the 
distance between those two 
points is calculated and 
displayed
13


key: chroma:document
string_value:
Compound Interest
114
calculates compound 
interest on an investment
user enters initial amount, 
interest rate & number of 
years
total = 
  amount*( +rate/100)years


key: chroma:document
string_value:
Math.random
in addition to the above math functions, JavaScript provides a function for 
generating a random number
◼ Math.random has no inputs, returns a random real number from the range [0, 1)
◼ note: smallest possible value = 0.0; largest possible value = 0.99999…
Math.random() → 0.3428794638
Math.random() → 0.8776243657
by itself, Math.random is not very useful
◼ but, can use in expressions to expand or shift the range
2*Math.random() → 2*(number from [0, 1) → number from [0, 2)
Math.random()+10 → (number from [0, 1)) + 10 → number from [10, 11)
X*Math.random()+Y → number from [Y, X+Y)
technically, it returns a pseudo-random number, 
since it uses a complex algorithm to generate 
numbers that appear random (using hidden 
inputs like the current time in milliseconds)
15


key: chroma:document
string_value:
Pick-4 Example
this page simulates picking 
4 numbered balls from 
lottery bins
to pick a random integer 
from 1 to numBalls
1. pick a # from the range 
[1, numBalls+1)
2. then round down
17


key: chroma:document
string_value:
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
1


key: chroma:document
string_value:
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
2


key: chroma:document
string_value:
Algorithms & CT
recall the four characteristics of computations thinking: DECOMPOSITION, PATTERN 
RECOGNITION, ABSTRACTION and ALGORITHM
▪ the final step in CT is formalizing the solution as an algorithm
▪ a clearly stated algorithm is a blueprint for future problem solving
consider the 2 algorithms (from Ch. C5) for finding the oldest person in a room
3
Algorithm 1
 Algorithm 2


key: chroma:document
string_value:
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 log2 of the number of people
◼ if you double the amount of people, the time needed to find the oldest person 
increases by the time required for one more round
4


key: chroma:document
string_value:
Algorithm Analysis (cont.)
when the problem size is large, performance differences 
 can be dramatic
for example, assume it takes 10 seconds to compare birthdays
◼ for algorithm 1:
 100 people → 10*100 = 1,000 seconds
 200 people → 10*200 = 2,000 seconds
 400 people → 10*400 = 4,000 seconds
 . . .
 1,000 people → 10*1,000 = 10,000 seconds
◼ for algorithm 2:
 100 people → 10* log2 100  = 70 seconds
 200 people → 10* log2 200  = 80 seconds
 400 people → 10* log2 400  = 90 seconds 
 . . .
 1,000 people → 10* log2 1,000,000  = 100 seconds
5


key: chroma:document
string_value:
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)
 
6


key: chroma:document
string_value:
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
7


key: chroma:document
string_value:
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
1. start at the beginning of the list
2. for each item in the list
i. examine the item - if that item is the one you are seeking, then you are 
done
ii. 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 
8


key: chroma:document
string_value:
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
1. initially, the potential range in which the item could occur is the entire list
2. as long as items remain in the potential range and the desired item has not 
been found, repeatedly
i. examine at the middle entry in the potential range
ii. if the middle entry is the item you are looking for, then you are done
iii. if the middle entry is greater than the desired item, then reduce the 
potential range to those entries left of the middle
iv. 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 home in 
on the value very quickly
9


key: chroma:document
string_value:
Figure8-6.png
Binary Search Example
suppose you have a sorted list of state names, and want to find MD
1. start by examining the middle entry (ND)
since ND comes after MD alphabetically, can eliminate it and all entries that appear to the right
2. next, examine the middle of the remaining entries (IA)
since IA comes before MD alphabetically, can eliminate it and all entries that appear to the left 
3. next, examine the middle of the remaining entries (MD)
the desired entry is found
10


key: chroma:document
string_value:
Search Analysis
sequential search
◼ in the worst case, the item you are looking for is in the last spot in the list (or 
not in the list at all)
 as a result, you will have to inspect and compare every entry in the list
◼ the amount of work required is proportional to the list size
→ 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 (330 million people)
◼ sequential search requires at most 330 million inspections/comparisons
◼ binary search requires at most log2(330,000,000) = 29 inspections/comparisons
11


key: chroma:document
string_value:
Another Algorithm Example
Newton’s Algorithm for finding the square root of N
1. start with an initial approximation of 1
2. as long as the approximation isn’t close enough, repeatedly
i. 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
 12


key: chroma:document
string_value:
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
13


key: chroma:document
string_value:
Evolution of Languages
the first programming languages were known as  
machine languages
◼ consist 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 and CPU registers
 very low level of abstraction
◼ machine language instructions are written in binary
 programming in machine language is tedious and error prone 
in early 1950s, assembly languages evolved from 
machine languages
◼ replaced binary codes with words like ADD, MOVE
 easier to remember & debug, but still machine-specific
◼ a separate program called an assembler translated the 
assembly instructions into machine language
14
in the late 1950's, high-level languages were 
introduced
◼ they allow the programmer to write code closer to the 
way humans think (as opposed to mimicking hardware 
operations)
◼ more natural, plus machine-independent


key: chroma:document
string_value:
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
real-world analogy: translating a speech from one language to another
15
an interpreter can be used provide a real-time translation
o the interpreter hears a phrase, translates, and immediately 
speaks the translation
o ADVANTAGE: the translation is immediate
o DISADVANTAGE: if you want to hear the speech again, must 
interpret all over again
a translator (or compiler) translates the entire speech 
offline
o the translator takes a copy of the speech, returns when the 
entire speech is translated
o ADVANTAGE: once translated, it can be read over and over 
very quickly
o DISADVANTAGE: must wait for the entire speech to be 
translated


key: chroma:document
string_value:
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
◼ particularly useful for dynamic, interactive applications (e.g., Web pages)
◼ each execution requires translating again, can be slow
◼ JavaScript is interpreted
16


key: chroma:document
string_value:
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, very fast
◼ used in large software applications when speed is of the utmost importance
◼ but must compile the entire program before execution, so initial delay
◼ C, C++, Java are compiled*
17


key: chroma:document
string_value:
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
◼ the user only needs to know how to call the function, not how it works
◼ simple user-defined functions similarly provide abstractions that 
simplify the page 1


key: chroma:document
string_value:
User-defined Functions
functions simplify the programmer's task
◼ minimize the amount of detail the developer must remember
e.g., to calculate a square root, only need to remember the name Math.sqrt
◼ minimize the size and complexity of code
e.g., simple user-defined functions in the head simplify buttons in the body
2
the general form of user -defined functions:
function FUNCTION_NAME(PARAMETER1, PARAMETER2, …) {
  STATEMENTS_TO_PERFORM_THE_DESIRED_COMPUTATION
  return OUTPUT_VALUE;
}
◼ parameters are variables that correspond to the inputs when the function is called
  will have as many parameters as there are inputs to the function (could be 0)
◼ a return statement specifies the output value for that function
 optional, as some functions don't return a value (e.g., write a message in page)


key: chroma:document
string_value:
Simple example
consider the following function for converting distances:
function InchesToCentimeters(inches) {
    cm = inches * 2.54;
    return cm;
}
◼ the function has one parameter, named inches
◼ when the function is called, an input value must be specified in the parentheses
InchesToCentimeters(10)
3
◼ the input value from the call is assigned to the parameter variable
◼ that variable can then be used in calculations (here, cm = 2.54*10 = 25.4)
◼ when a return statement is reached, the expression is evaluated and returned
a function call can appear in any expression
◼ the return value is substituted for the call when evaluating
outputP.innerHTML = InchesToCentimeters(10);     displays 25.4 in outputP


key: chroma:document
string_value:
Simple example (cont.)
4
as with any variable, parameter names should convey their purpose:
◼ inches, distanceInInches, lengthInInches, …
convention used throughout the book:
◼ variable/parameter names start with a lowercase letter
◼ function names start with an uppercase letter
◼ if a variable name consists of multiple words, use internal capitalization
since a return statement can specify an expression, we could equivalently 
define the function as:
function InchesToCentimeters(distanceInInches) {
    return distanceInInches * 2.54;
}


key: chroma:document
string_value:
Conversion Page
note 2 function 
definitions in head
still need 
parameterless 
function 
connected to the 
button
5
this shows that a function can 
contain a call to another function


key: chroma:document
string_value:
Pick-4 Revisited
InchesToCentimeters is easy to understand, but not very motivational
for a better example, consider the Pick -4 page from Chapter X5
◼ used Math.random to generate random lottery balls in the range 1..numBalls
 pick1 = Math.floor(numBalls*Math.random() + 1);
 pick2 = Math.floor(numBalls*Math.random() + 1);
 pick3 = Math.floor(numBalls*Math.random() + 1);
 pick4 = Math.floor(numBalls*Math.random() + 1);
◼ tricky, messy, difficult to modify (e.g., suppose we learned balls started at 0)
6
better solution: capture the tricky expression in a function
function RandomInt(low, high) {
  return Math.floor(Math.random()*(high-low+1)) + low; 
}
◼ once defined & tested, can be used anywhere a random integer is needed


key: chroma:document
string_value:
Pick-4 with Function
RandomInt function makes the 
code much easier to 
understand & modify
e.g., for balls starting at 0:
pick1 = RandomInt(0, numBalls-1); 
pick2 = RandomInt(0, numBalls-1); 
pick3 = RandomInt(0, numBalls-1); 
pick4 = RandomInt(0, numBalls-1); 
7


key: chroma:document
string_value:
More Examples
8
parameters & return 
values can be strings
function for calculating 
point distance (Ch. X5)
function for calculating 
compound interest (Ch. 
X5)
function for calculating 
square root (using 
Newton's algorithm from 
Ch. C6)


key: chroma:document
string_value:
Triangle Page
recall distance.html page from Ch. X5
▪ can simplify by adding Distance function
functions are especially useful if the 
calculation is performed multiple times
▪ here, need to calculate the lengths of three 
triangle sides
▪ define the complex distance calculation once 
in the function
▪ can then call the function repeatedly
9


key: chroma:document
string_value:
Function libraries
functions such as RandomInt can be added to head of a page
◼ tedious if functions are to be used in many pages
◼ involves creating lots of copies that all must be maintained for consistency
the alternative for general purpose functions is to place them in a library file
◼ a library file is a separate text file that contains the definitions of one or more 
JavaScript functions
◼ by convention, function library files end in .js since they contain JavaScript code
e.g., http://compsciconcepts.com/random.js
10


key: chroma:document
string_value:
Function libraries
once a function library file has been created, it can be loaded into any page by 
adding a script element whose src is that file
<script src="LIBRARY FILENAME"><script>
◼ this new script elements is added to the head of the page
◼ note that no actual code appears in between the script tags 
the code from the library is inserted the script element when the page loads
advantages of library files:
◼ avoid duplication (only one copy of the function definition)
◼ easier to reuse functions (simply load the library file into any page)
◼ easier to modify functions (a single change to the library file automatically 
affects all pages that load the library
11


key: chroma:document
string_value:
note: there is one script 
element for loading the 
library
◼ this makes the RandomInt 
function accessible within the 
page
there is separate script 
element for defining the 
page-specific function
◼ this function can call the 
library function that has been 
loaded
Pick-4 Yet Again
12


key: chroma:document
string_value:
Dice Example (v. 1)
this page uses the 
RandomInt function 
from random.js to 
pick the random die 
images
note: die images are 
named die1.gif, 
die2.gif, …, die6.gif
13


key: chroma:document
string_value:
Dice Example (v. 2)
alternatively, could use 
the RandomOneOf 
function from the 
random.js library to 
pick the die images
note: function input 
must be a list of options, 
contained in [ ] and 
separated by commas
14


key: chroma:document
string_value:
Sequences Example
consider the task of generating 
random character sequences
 e.g., for creating secure passwords
the user can specify the 
characters to choose from in 
the text box
uses the RandomChar function 
from random.js to pick 3 
random characters & 
concatenate them
15


key: chroma:document
string_value:
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
◼ provide units of computational abstraction – user can ignore details
when you write a general-purpose function that could be used in many pages
◼ create a library file and package that function with related functions
◼ these can then be loaded into pages that need those functions
when you define a function that is page -specific:
◼ define it in the head of that page (within a script element)
◼ can have more than one function defined in the same script element
16


key: chroma:document
string_value:
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
1


key: chroma:document
string_value:
Artificial Science
many activities carried out by computer scientists utilize 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
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


key: chroma:document
string_value:
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"
2


key: chroma:document
string_value:
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
3


key: chroma:document
string_value:
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
4


key: chroma:document
string_value:
Software
software refers to the programs that execute on computers
3 basic software categories
1. systems software: programs that directly control the execution of hardware 
components (e.g., operating systems)
2. development software: programs that are used as tools in the development of 
other programs (e.g.  Microsoft.NET, Java SDK)
3. 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
5


key: chroma:document
string_value:
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 tape on which characters can be written (I/O)
  a processor that can read/write on the tape, move left or right (CPU)
  space for storing the machine state - a number (memory)
◼ 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!
6


key: chroma:document
string_value:
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
4 highly visible subfields
1. algorithms and data structures
2. architecture
3. software engineering
4. artificial intelligence and robotics
7


key: chroma:document
string_value:
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
8


key: chroma:document
string_value:
Private-key Encryption
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., Advanced Encryption Standard (AES) utilizes 256-bit keys (2256 ≈ 1077 
possibilities)
note: the private key must be shared securely
◼ face-to-face meeting? guarded courier?
◼ not feasible for online commerce 9


key: chroma:document
string_value:
Public-Key Encryption
in 1976, Whitfield Diffie and Martin Hellman proposed a new approach
◼ instead of a single, private key, public-key encryption utilizes a pair of keys
 a public key is used to encrypt messages
 a private key is required to decrypt the message
◼ the only way to decrypt a message encrypted with a public key is using 
the corresponding private key
 as long as the recipient keeps the private key secure, they are free to share 
the public key with anyone
10


key: chroma:document
string_value:
Encryption and e-commerce
public-key encryption is the basis of almost all secure communication over the 
Internet
◼ without it, e-commerce would not be possible
◼ consider what happens when you buy something online
public-key encryption is also used whenever you surf the Web with https:// 
or use a secure Wi-Fi connection 11


key: chroma:document
string_value:
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 and i3 processors are dual core - integrate the circuitry for 2 processors
 can execute two different instructions simultaneously, potentially double execution speed
 similarly, i5 and i7 have 4 cores, i9 has 8 cores
◼ e.g., high-end Web Servers utilize multiple processors
 can service multiple requests simultaneously by 
 distributing the load among the processors
◼ IBM's Deep Blue contained 32 general-purpose 
processors and 512 special-purpose chess processors
 worked in parallel to evaluate 200 million chess


key: chroma:document
string_value:
distributing the load among the processors
◼ IBM's Deep Blue contained 32 general-purpose 
processors and 512 special-purpose chess processors
 worked in parallel to evaluate 200 million chess 
moves per second)
 first computer to beat a world champ (1997)
◼ its descendent, Watson, contains 2,880 processors
 won Jeopardy challenge in 2011
 used in many applications (weather modeling, 
medical diagnosis, satellite imagery analysis)
12


key: chroma:document
string_value:
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
◼ the adoption of the object-oriented programming methodology has made it 
easier to reuse code
 13


key: chroma:document
string_value:
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, credit card fraud detection)
 neural computing – design of architectures that mimic the brain
neural networks are used in handwriting analysis, self-driving cars, facial recognition, …
14


key: chroma:document
string_value:
Bioinformatics
multi-disciplinary field 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 15


key: chroma:document
string_value:
Data Science
data science utilizes concepts and methods from computer science, math and 
statistics to predict outcomes and extract insights from collections of data
◼ supervised learning: learn to predict future outcomes based on past behavior
 predicting the fluctuations in the stock market based on past performance
 Amazon predicting which products you may want based on past purchases
 Netflix predicting which shows you might like based on your viewing history
◼ unsupervised learning: process data to discover patterns and extract insights
 a baseball team discovering player tendencies or weaknesses
 a government agency using data insights to set policy
16


key: chroma:document
string_value:
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
17


key: chroma:document
string_value:
Biology
biology is roughly defined as "the study of life"
◼ it is concerned with the characteristics and behaviors of organisms, how 
species and individuals come into existence, and the interactions they 
have with each other and with the environment 
(en.wikipedia.org/wiki/Biology )
biology encompasses a broad spectrum of academic fields that are 
often viewed as independent disciplines 
◼ ecology and evolutionary biology study life at the habitat or population 
level
◼ developmental biology and genetics study life at organism level
◼ physiology, anatomy, and histology study life at the multicellular level
◼ cell biology studies life at the cellular level
◼ molecular biology, biochemistry, and molecular genetics study life at the 
atomic and molecular level
1


key: chroma:document
string_value:
Impact of Computers
the history of biology dates as far back as the rise of various civilization 
◼ while computers are relatively new, they have had a monumental impact on 
biological research
3 examples of impact:
1. computer technology is rapidly advancing the tools of scientific research 
2. computer models are being used to study complex systems
3. computers are being used to store, process, and analyze large collections of 
biological data
note: this list is in no way exhaustive
◼ many aspects of biology and computer science are converging
◼ biology researchers must be savvy computer users and even programmers
◼ computer scientists must be able to solve interdisciplinary problems  
2


key: chroma:document
string_value:
Technology Tools/Resources
many of the traditional tools of biological research are integrating computer 
technology
e.g., the confocal microscope
 invented by Marvin Minsky (computer science pioneer)
 works by focusing a laser on a dyed sample and
 measuring the fluorescent light emitted
 can be used to build up a 3-D model of a sample, stored on
 a computer
e.g., DNA Microarrays to measure the expression levels of genes 
the Internet and the Web allow researchers to 
share data and publications
◼ speeds the dissemination of information and 
the advancement of science
e.g., PubMed, from the National Library of 
Medicine 3


key: chroma:document
string_value:
System Modeling
as computer memory and processing power has increased, it has become 
possible to model complex biological systems in software
◼ can attempt to discern natural laws or behaviors by observing the model under 
varying conditions
 e.g., models of plant or seashell growth
 e.g., the evolution of cooperative behavior in species, such as bird flocking
◼ can predict the effects of actions over long periods  
 e.g., the effects of automobile emissions on global warming
 e.g., the effects of increased fishing on worldwide fishery stocks
◼ can avoid infeasible, unethical, or costly experimentation
 e.g., predict the toxicity of a new drug based on a chemical/biological model as opposed 
to animal testing
 e.g., study brain trauma using a neural network model
4


key: chroma:document
string_value:
Ecosystem Modeling
in the late 1960s, John Conway showed that a simple 
model of an environment could produce complex and 
interesting behavior
▪ the environment is modeled as a 2-D grid of cells
▪ a cell can be alive (contain an organism) or dead
▪ simple rules model evolution
1. a dead cell becomes alive in the next generation if it has exactly 
3 neighbors 
2. a living cell survives in the next generation if it has 2 or 3 
neighbors 
Conway's ideas have been extended to a variety 
of ecosystems
▪ here, different colored cells denote different 
organisms (sharks & fish)
▪ other systems have modeled:
✓ the growth of viruses 
✓ the spread of infectious diseases in a 
population
✓ the behavior of an ant colony
 5


key: chroma:document
string_value:
Bioinformatics
perhaps the biggest impact of computers in biology is in storing, accessing, 
and processing large amounts of biological data
the new field of bioinformatics bridges biology and computer science (or 
informatics, as it is known in Europe)
◼ broad definition of bioinformatics: the use of computer science techniques to 
solve biological problems
◼ narrower but common definition:  the application of computer science techniques 
to the representation and processing of biological data
as research tools advance, biologists are generating enormous amount of 
data
◼ a single experiment with genetic material can produce thousands or millions of 
data points
◼ computational and statistical tools are needed to analyze and understand such 
volumes of data
6


key: chroma:document
string_value:
DNA Overview
DNA is the genetic blue -print of life
◼ made of nucleotides with four bases (A, T, G, C), 
organized in a double-helix 
◼ the two strands match A+T and C+G base pairs
◼ can think of DNA as encoding information in base 4
a gene is a region of DNA that encodes the 
chemical structure of a protein
◼ proteins (e.g., enzymes, hormones, antibodies) 
control cellular and organ functions
it is currently believed that there are 20,000 -
30,000 different genes in human DNA
◼ roughly 3 billion base pairs
"If our strands of DNA were stretched out in a line, the 46 chromosomes making 
up the human genome would extend more than six feet. If the ... length of the 100 
trillion cells could be stretched out, it would be ... over 113 billion miles. That is 
enough material to reach to the sun and back 610 times." [Source: Centre for 
Integrated Genomics] 7


key: chroma:document
string_value:
DNA Databases and Tools
often, the source or 
purpose of a DNA 
sequence can be 
determined by 
comparing it with 
documented genetic 
material 
◼ several large 
databases are 
available online
◼ tools for visualizing 
and/or searching the 
databases are also 
available
e.g., the Ensemble site 
(www.ensembl.org) 
contains visualizations 
of the human genome 
and other DNA 
sequences 
8


key: chroma:document
string_value:
GenBank
the GenBank public 
repository of DNA and 
RNA sequence data 
contains 
◼ partial or complete 
genomes for more 
than 300,000 
organisms
◼ more than 1 trillion 
bases of sequence 
data
◼ roughly 250 million 
new DNA sequences 
are added per month
the database can be 
accessed and searched 
using various tools at 
www.ncbi.nlm.nih.gov
9


key: chroma:document
string_value:
Analog vs. Digital
there are two ways data can be stored electronically 
1. analog values represent data in a way that is analogous to real life 
◼ signals can vary continuously across an infinite range of values 
2. digital values utilize only a finite set of values 
1


key: chroma:document
string_value:
Analog/Digital Tradeoffs
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
when storing data on a computer, reproducibility is paramount
◼ changing a single bit in a file can drastically change the data
modern computers save and manipulate data as discrete (digital) values
◼ the most effective systems use two distinct (binary) states for representing data
◼ in essence, all data is stored as binary numbers
2


key: chroma:document
string_value:
Binary Numbers
in the binary number system, all values are represented using only 
the two binary digits 0 and 1, which are called bits
   
 
  
we can also refer to bits by index
▪ rightmost bit is index 0 (representing 20 = 1s place)
▪ next from right is index 1 (representing 21 = 2s place
▪ next over is index 2 (representing 22 = 4s place
▪ . . .
▪ ith index (from right) represents 2i s place
3
note: 
• all even numbers end with a 0 bit; odd numbers with 1 bit WHY?
• adding a 0 bit at the end it doubles its value  WHY?


key: chroma:document
string_value:
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)
6


key: chroma:document
string_value:
Representing Real Numbers
a real number can be uniquely identified by the two components of its 
scientific notation (fractional part and the exponent)
 123.456 = 0.123456 x 103 0.0099 = 0.99 x 10-2
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
7


key: chroma:document
string_value:
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
 8


key: chroma:document
string_value:
Representing Text
strings can be represented as sequences of ASCII/Unicode 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/Unicode codes
◼ e.g., word processing programs will insert special character symbols to denote 
formatting (analogous to HTML tags in a Web page)
9


key: chroma:document
string_value:
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
10


key: chroma:document
string_value:
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
1


key: chroma:document
string_value:
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:
if (BOOLEAN_TEST) {
    STATEMENTS_EXECUTED_IF_TRUE
}
else {
    STATEMENTS_EXECUTED_IF_FALSE
}
note: indentation is not required, but it is STRONGLY 
RECOMMENDED to make an if statement readable
2


key: chroma:document
string_value:
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
the Boolean test in an if statement determines the code that will be executed 
◼ if the test succeeds (evaluate to true), then the code inside the subsequent 
curly braces will execute
◼ if the test fails (evaluates to false), then the code inside the curly braces 
following the else will execute
◼ note that if the test fails and there is no else case, the program moves on to 
the statement directly after the if
NOTE: 
== is for comparisons 
= is for assignments
3


key: chroma:document
string_value:
If Statement Examples
an if statement is known as a control statement, since its purpose is 
to control the execution of other statements 
4


key: chroma:document
string_value:
Input Verification
here, an if statement checks to 
see if number box is empty (i.e., 
its value attribute is '')
▪ if empty, displays an alert warning
▪ if not, calculates & displays letter 
grade as before
note: an if statement can be 
nested inside another if 
statement 6
common use of if statement:
▪ verify that user input has been entered
▪ warn the user if not


key: chroma:document
string_value:
Input Verification
similarly, could add an if statement 
to the tip calculator to make sure 
the user entered a check amount
▪ what about the tip percent?
7


key: chroma:document
string_value:
Cascading If-Else
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: three different grade levels
◼ A-level (grade ≥ 90), passing (60 ≤ grade < 90), failing (grade < 60)
◼ the outer if-else distinguishes A from non-A grades
◼ the nested if-else further separates non-A grades into passing and failing
8


key: chroma:document
string_value:
Cascading If-else Structure
nested if-else statements are known as cascading if-else structures 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-else structure
◼ if the test fails, then control cascades down to the next if test
◼ in general, control cascades down the structure from one test to another until 
one succeeds or the end of the statement is reached
9


key: chroma:document
string_value:
A Cleaner Notation
when it is necessary to handle a large number of alternatives, nested if -else 
structures can become unwieldy
◼ multiple levels of indentation and curly braces cause the code to look cluttered 
make it harder to read/understand
◼ can simplify by removing some unnecessary curly braces & aligning each case to 
the left
        nested if statements            vs.           more readable if-else
10


key: chroma:document
string_value:
Letter Grade (cont.)
as before, the student's 
average is entered in a 
number box
the cascading if-else 
structure determines the 
corresponding letter grade
11


key: chroma:document
string_value:
Embedded Counters
recall the dice pages from Chapter X6
suppose we wanted to keep a count of the number of rolls
◼ we could use a span element to store the count (initially 0)
Number of rolls: <span id="rollSpan">0</span>.
◼ for each roll, access the count, add 1, and reassign
rollSpan.innerHTML = rollSpan.innerHTML + 1;       // DOES NOT WORK
12
problem: innerHTML always evaluates to a string
◼ rollSpan.innerHTML + 1 = '0' + 1 = '0' + '1' = '01'       (see Ch. X5)
we avoided this problem with number boxes using valueAsNumber
◼ unfortunately, there is no equivalent attribute for a span
◼ fortunately, there is a function that will convert a string into its equivalent number value
rollSpan.innerHTML = Number(rollSpan.innerHTML) + 1;       // THIS WORKS!


key: chroma:document
string_value:
Dice Stats (v.1)
recall the pages from Ch X6 
that simulated dice rolls
add an embedded counter
▪ initially, the span contains 0
▪ its contents are incremented 
each time function is called
also add a function to reset the 
counter
13


key: chroma:document
string_value:
Conditional Counters
counters can be combined with if statements to count conditional events
◼ e.g., to count doubles
 if (roll1 == roll2) {
   doubleSpan.innerHTML = Number(doubleSpan.innerHTML) + 1;
 }
◼ e.g., to count sevens
 if (roll1+roll2 == 7) {
   sevenSpan.innerHTML = Number(sevenSpan.innerHTML) + 1;
 }
14
since doubles and sevens are mutually exclusive, could even combine
 if (roll1 == roll2) {
   doubleSpan.innerHTML = Number(doubleSpan.innerHTML) + 1;
 }
     else if (roll1+roll2 == 7) {
   sevenSpan.innerHTML = Number(sevenSpan.innerHTML) + 1;
 }


key: chroma:document
string_value:
Dice Stats (v.2)
to keep stats on doubles and 7s
▪ add spans to the page to keep 
track of the # of doubles and # 
of sevens
▪ add if-else to conditionally 
increment the counters
▪ also update ResetCounts to 
that all counters are reset
 
15


key: chroma:document
string_value:
Boolean Expressions
sometimes, simple comparisons between two values may not be adequate to 
express the conditions under which code should execute
complex Boolean expressions can be built using logical connectives
TEST1 && TEST2 evaluates to true if TEST1 AND TEST2 are true
TEST1 || TEST2 evaluates to true if TEST1 OR TEST2 arise true
! TEST  evaluates to true if TEST is NOT true
if (roll1 == 4 && roll2 == 4) { 
  CODE_TO_BE_EXECUTED_IF_4-4_COMBINATION_IS_ROLLED
}
if (roll1 == 4 || roll2 == 4) { 
  CODE_TO_BE_EXECUTED_IF_EITHER_ROLL_IS_4
}
if (!(roll1 == 4 && roll2 == 4)) { 
  CODE_TO_BE_EXECUTED_ IF_4-4_COMBINATION_IS_NOT_ROLLED
} 16


key: chroma:document
string_value:
Dice Stats (v.3)
to also keep stats on natural 7s
▪ add a test for 3-4 or 4-3 
combinations
▪ since the test is inside the 
sevens case, will only be 
executed if the roll is a seven
▪ then, if roll1 is a 3 or a 4, 
increment naturalSpan
17


key: chroma:document
string_value:
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 values 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 values cannot be reproduced exactly,
but this is not usually a problem since the 
human ear is unlikely to notice small 
inconsistencies
tuning 
fork
violin
piano
waterfall
1


key: chroma:document
string_value:
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 
2


key: chroma:document
string_value:
Representing Sounds (cont.)
to play a digital recording, a music player must extract the numbers and 
reconstruct the analog waveform
3
since there are gaps between measurements, the reconstruction will not be an 
exact reproduction of the original
▪ CD takes 44,100 measurements/second, so gaps are small and the 
resulting sound is high -quality


key: chroma:document
string_value:
Sound compression
CD-quality sound requires significant storage
consider a 3-minute, stereo recording (meaning two separate tracks)
▪ assume each measurement is stored using 2 bytes
3 min x 60 sec/min x 2 tracks x 44,100 nums/sec x 2 bytes/num = 31.752 MB
4
since the typical music album contains 10 -20 songs, CD storage requires:  
317-634 MB of space
▪ this will fit on a 700 MB disk, but would quickly overwhelm 
smartphones and portable music players
also, file size makes downloading or streaming music problematic
4G wireless connection can typically download up to 1.5 MB/second
▪ to download 3 min song: 31.752 MB / 1.5 MB/sec = 21 seconds
▪ to download 20 song album: 634 MB / 1.5 MB/sec = 7 minutes


key: chroma:document
string_value:
Sound compression (cont.)
fortunately, techniques have been developed to reduce file size
▪ e.g., filter out sounds beyond the range of human hearing
▪ e.g., recognize when one track masks another
▪ e.g., possibly even simplify the waveform
the MP3 format (introduced in 1993) uses techniques such as these to reduce 
file size by 75-95% 
▪ 3 minute song: 31.752 x 0.05 = 1.6 MB = 1 second using G4
▪ 20 song album = 634 MB x 0.05 = 31 MB = 20 seconds using G4
MP3 is a lossy format
▪ to achieve that level of compression, it makes simplifications and loses 
some of the information in the waveform
▪ this results in lower sound quality when played
5


key: chroma:document
string_value:
Impact on the music industry
before the CD in 1982, music piracy was almost non -existent
▪ few people had the technology to copy a phonograph record
▪ recording a cassette was easy, but the sound quality was bad
▪ CDs changed the game
o cheap devices for making perfect, digital copies were readily available
o this panicked the music industry, led to MANY piracy prosecutions
6
before the MP3 format in 1993, 
streaming music was not feasible
▪ now, phones & portable players 
are the primary music source for 
many
▪ other digital audio formats have 
followed, e.g., WAV, AIFF, M4P.


key: chroma:document
string_value:
Representing Images
like sound, images are inherently analog
◼ real-world colors come in an infinite variety of shades
◼ film photography creates an analog representation using light-sensitive chemicals
like sound, techniques exist for digitizing images
◼ the simplest involves partitioning the image into a grid of picture elements (pixels) 
and then converting each pixel into a bit pattern
◼ the digital representation is known as a bitmap
7


key: chroma:document
string_value:
Image resolution
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 72 pixels per square inch, each subsequent image has 
half the resolution
8
this is a grayscale image
◼ each pixel is a shade of gray, somewhere between black and white
◼ most image formats use 8 bits for a grayscale pixel → 256 shades of gray
◼ as a result, grayscale requires 8x storage of black-and-white


key: chroma:document
string_value:
Color images
for color images, can break each color into its red, green & blue components
◼ RGB value is a triple, listing the intensities of red, green & blue on a 0-255 scale
◼ 2563 = 16,777.216 different color combinations can be represented
◼ each component requires 8 bits, so a total of 24 bits per pixel
→ color images require 3x storage of grayscale, 24x the storage of black-and-white
9
experiment with http://compsciconcepts.com /C9/rgb.html


key: chroma:document
string_value:
Image compression
color bitmaps can be extremely large
◼ 12 megapixel image → 12 million pixels → 36 MB of storage
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
 25-50% reduction possible
◼ PNG(Portable Network Graphics)
 more modern, lossless alternative to GIF - more colors
 10-50% smaller than GIF (so 33-75% reduction from bitmap)
◼ JPEG (Joint Photographic Experts Group)
 a lossy format, so the compression is not fully reversible (but more efficient) 
 commonly used for photographs
 90-95% reduction possible
image formats also embed metadata (date, location, source, …) in images
◼ can be useful for tasks such as organizing a photo gallery by data or geography 10


key: chroma:document
string_value:
Steganography
an interesting side topic related to images is steganography
◼ the practice of hiding a secret message in plain sight (e.g., within another 
message or object)
1. Take your secret message an encode it as bits (using ASCII/Unicode codes):       
b1 b2 b3 b4 b5 b6 b7 b8 b9 ... 
2. Take an image and break it into its RGB pixels:  (R1,G1,B1) (R2,G2,B2) (R3,G3,B3) …
3. For each bit bi in the message, possibly change the Bi component of the 
corresponding pixel so that:
o if bi is even, then Bi is also even (add 1 to Bi if necessary)
o if bi is odd, then Bi is also odd (add 1 to Bi if necessary)
the resulting image will look the same to the human eye
◼ e.g., most people can't distinguish between (20, 50, 100) and (20, 50, 101)
but, if you know to look, you can extract the message bits from the pixels
11


key: chroma:document
string_value:
Example:
suppose the message starts with 'M' (whose ASCII value is 01001101)
and the image starts with pixels:
(100,200,50) (100,200,50) (100,202,52) (98,203,53) (88,190,48) (88,188,47) (86,180,40) (80,160,43)
then, embed the message bits in the B components of the pixels:
(100,200,50) (100,200,51) (100,202,52) (98,203,54) (88,190,49) (88,188,47) (86,180,40) (80,160,43)
to an unsuspecting viewer, the image will look normal
to a person who knows to look, the message bits can easily be extracted
(100,200,50) (100,200,51) (100,202,52) (98,203,54) (88,190,49) (88,188,47) (86,180,40) (80,160,43)
                                                                                       
          0              1              0            0             1             1            0            1
12


key: chroma:document
string_value:
Representing movies
in principle, a movie is a sequence of images 
(frames) that are displayed in sequence to 
produce the effect of motion
◼ typically, 24 frames/sec
MPEG or MP4 format uses a variety of techniques to 
compress video
◼ individual frames use techniques similar to JPEG
◼ since much of successive frames are same, need 
only store changes from frame to frame
elements of MPEG are included in the ATSC 
(Advanced Television Systems Committee) 
standard for digital TV
◼ individual frames use techniques similar to JPEG
other related formats are DVD & Blu -Ray
13


key: chroma:document
string_value:
ASCII movies
for a fun and creative 
exercise, make your 
own movies
each frame is "drawn" 
using characters 
from the keyboard
frames are separated 
using =====
the button will "play" 
the movie, 5 
frames/second
14


key: chroma:document
string_value:
Software Models
when studying complex systems (e.g., weather, stock markets, voting), 
software models provide a fast & cost -effective tool for gaining insights
◼ computer simulations can be much faster than real-world counterparts
e.g., can simulate centuries of climate change in seconds
◼ can be much cheaper to simulate than to study the real-world system
e.g., can try different investment strategies without risking real money
◼ can control for parameters that are difficult to obtain reliably in real-world
e.g., can speculate on how changes in demographics would affect an election
we will consider 2 examples of modeling real -world systems
1. disease spread 
2. volleyball game
software models always make simplifying assumptions
◼ must always be careful to examine the model and make sure that the 
simplifications do not invalidate conclusions drawn from the simulations
1


key: chroma:document
string_value:
Disease Spread
when there is a disease outbreak (e.g., COVID -19), the CDC and other health 
organizations build software models to 
◼ better understand and warn the public about the disease
◼ study potential interventions (e.g., social distancing, vaccines)
these models can be very complex, taking into account:
◼ transmission method, patient incubation period, population density, …
a very simple model uses the basic reproduction number , R0: the number of 
people that a patient will infect over the course of their infection  
◼ if R0 < 1, then each patient infects fewer than 1 other (on average), so the disease 
will eventually die out
◼ if R0 = 1, then each patient infects exactly 1 other (on average), so the disease 
spreads steadily (known as an endemic)
◼ if R0 > 1, then each patient infects more than 1 other (on average), so the disease 
spreads exponentially (known as an epidemic or pandemic)
2


key: chroma:document
string_value:
R0 Example
suppose a disease has R 0 = 2, 100 people infected:
1. in 1st wave, those 100 patients infect 200 (2 per person on average)
2. in 2nd wave, the 200 patients from wave 1 infect 400 
3. in 3rd wave, the 400 patients from wave 2 infect 800
     . . .
10. in 10th wave, the 51,200 patients from wave 9 infect 102,400
3
estimated R0 for common diseases:
◼ seasonal flu   R0 ≈ 0.9-2.1
◼ Smallpox   R0 ≈ 7
◼ Polio   R0 ≈ 7
◼ Measles   R0 ≈ 18
◼ COVID-19 in U.S., March 2020 R0 ≈ 4
◼ COVID-19 in U.S., October 2020 R0 ≈ 2
◼ COVID-19 in U.S., March 2021 R0 ≈ 0.9
note: R0 is not fixed – medical 
treatments and behavior changes 
can affect it
fortunately, vaccines have been 
developed for many highly 
contagious diseases


key: chroma:document
string_value:
Disease Spread Example
similar to Hailstone & compound 
interest examples from Ch. X8
▪ currentWave counter controls 
the loop
▪ currentCases calculates the 
new cases each wave
▪ totalCases sum keeps track of 
the total number of cases
4
Graphical user interface, text
Description automatically generated


key: chroma:document
string_value:
Modeling Tradeoffs
advantages:
◼ CONVENIENCE: software models can be executed anywhere sufficient computer 
power is available 
◼ SAFETY: since software models run on a computer, they pose no risk to patients 
or researchers
◼ SPEED: the speed at which software models can be executed is only limited by 
the complexity of the model and the processing power of the computer
◼ CUSTOMIZABILITY: software models are typically built with parameters that 
can be adjusted to test different conditions
◼ REPRODUCABILITY: as they are fast and customizable, software models can 
be repeated to confirm results and compare outcomes under different conditions
6
disadvantages:
◼ OVERSIMPLIFICATION: by their very definition, software models simplify the 
systems they are modeling, potentially ignoring factors that may be important
◼ INCORRECTNESS: as with any software system, software models can contain 
errors that impact the results
◼ OVERCONFIDENCE: due to flaws in design or implementation, model can


key: chroma:document
string_value:
◼ INCORRECTNESS: as with any software system, software models can contain 
errors that impact the results
◼ OVERCONFIDENCE: due to flaws in design or implementation, model can 
produce results that look reasonable but are incorrect or misleading


key: chroma:document
string_value:
Nondeterministic Models
the R0 model of disease spread is deterministic
◼ it follows rules that unambiguously determine the output
◼ i.e., same inputs will always produce the same output
many real-world systems are too complex to model deterministically
◼ instead, they utilize probabilities to capture unpredictable features
◼ i.e., same input should produce similar but not necessarily identical results
7
consider a nondeterministic model of disease spread
◼ each day, an infectious patient has a certain probability of infecting those with 
whom they come in contact
◼ allows us to introduce more complex variables: locality & infectious period
◼ e.g., once infected, a patient will be contagious for 4 days & have 20% probability 
of infecting those with whom they come in contact


key: chroma:document
string_value:
2-D Disease Spread
the user can control 
▪ the size of the grid
▪ infection probability
▪ contagious period
initially, there is a single 
infected person at the 
center of the grid
can click a button to see:
▪ a single day
▪ a series of days (with 
delays in between)
8
Graphical user interface, application
Description automatically generated


key: chroma:document
string_value:
2-D Disease Spread
white square: uninfected 
person
black square: infect & 
contagious person
gray square: infected but 
no longer contagious
the simulation is highly 
sensitive to changes in 
the infection rate & 
contagious period
9


key: chroma:document
string_value:
Volleyball Simulations
in 1998, FIVB switched the scoring system for international volleyball
◼ old system: sideout scoring – only serving team can win a point
◼ new system: rally scoring – a point is awarded on every rally
◼ the goal was to make games more exciting and more consistent in length
in conjunction, they extended games from 15 points to 25 points
◼ the new game length was intended to maintain competitive balance
HOW DID THEY DETERMINE THE NEW GAME LENGTH?
for our model:
◼ assume each team has a ranking (1-100) that quantifies their strength
◼ by comparing team strengths, can determine the likelihood of winning a rally 
  e.g., if team1 is 80 and team2 is 40, team1 twice as likely to win a given rally
◼ to simulate a game, repeatedly simulate points and keep score
the game is over when a team reaches 25 points (must win by 2)
10


key: chroma:document
string_value:
Simulation Details
the following is a general layout of the simulation
score1 = 0;
score2 = 0;
       
while (GAME_NOT_OVER) {
  DETERMINE_WINNER_OF_RALLY
  if (TEAM1_WON_RALLY) {
    score1 = score1 + 1;
  }
  else {
    score2 = score2 + 1;
  }
         
  DISPLAY_SCORE
}
need to figure out the 
loop condition
also need to figure out 
how to simulate a rally
11


key: chroma:document
string_value:
Simulation Details
if we ignore the win-by-2 rule, the loop test is straightforward
  while (score1 < 25 && score2 < 25) {
be careful with loop tests 
◼ they are not stopping conditions, they are continuing conditions
◼ the game continues as long as both teams are under 25 points
12
the win-by-2 condition adds another possibility of continuing
◼ continue if both teams are under 25 points OR within 1 point of each other
 while ((score1 < 25 && score2 < 25) ||  
     (Math.abs(score1-score2) < 2)) {


key: chroma:document
string_value:
Simulation Details
to simulate a single rally, we need to pick the winner probabilistically
◼ if team1 is X% better, they should be X% more likely to win any given rally
◼ we can simulate this using RandomInt (from the random.js library)
1. generate a random integer in the range 1 to (strength1+strength2)
2. if that random integer <= strength1, then team1 wins the rally
3. otherwise, team2 wins the rally
◼ e.g., suppose team1 has strength 50 and team2 has strength 50
if pick a random number in 1…100, it is equally likely to be 1..50 as 51..100
◼ e.g., suppose team1 has strength 80 and team2 has strength 40
if pick a random number in 1…120, it is twice as likely to be 1..80 as 81-120
13


key: chroma:document
string_value:
Simulating Many Games
with any nondeterministic model, need to perform a large number of 
simulations to obtain statistically meaningful results
◼ with only a small number, lucky/unlucky streaks can greatly skew the results
◼ e.g., 7 HEADS out of 10 coin flips would not shock you, 700 out of 1,000 should
if we want to simulate thousands of games, we don't need to see 
point-by-point scores
◼ similar to roll stats example from Ch. X8, simply keep a counter of wins/losses and 
display the final result when done
15
1. remove the statements from PlayGame that display the score
2. instead, add an if statement at the end of the function that determines the winner 
and returns either 'team1' or 'team2'
3. define a function that simulates a specified number of games (by calling PlayGame 
inside a loop) and keeps count of wins by team1


key: chroma:document
string_value:
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
1


key: chroma:document
string_value:
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
2


key: chroma:document
string_value:
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
3
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


key: chroma:document
string_value:
Transistors
as we saw in Chapter C4, advances in switching technology have defined the 
generations of computers
◼ 1930’s – electromagnetic relays served as physical switches, with on/off 
positions 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
4
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


key: chroma:document
string_value:
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


key: chroma:document
string_value:
Transistors as Switches
a PMOS transistor is positively doped, so that the switch is ON (or closed) 
when there is no current on the control wire, but OFF (or open) when 
current is applied
5
transistors can be combined with other electronic components to form 
circuits, which control the flow of electricity in order to produce a particular 
behavior


key: chroma:document
string_value:
From Transistors to Gates
consider the following circuit combining a PMOS transistor with a power 
supply
◼ note: the power supply is connected to the transistor input wire, the circuit input 
is connected to the control wire
◼ if no current (0 volts) is applied to the circuit input wire, the transistor will be ON 
to allow current to travel on the output wire
◼ if current (5 volts) is applied to the circuit input wire, the transistor will be OFF 
so no current reaches the output wire
◼ the result is that the output is the opposite of the input 
◼ this circuit known as a NOT gate
6


key: chroma:document
string_value:
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
7
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


key: chroma:document
string_value:
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
8


key: chroma:document
string_value:
Gates and Binary Logic
◼ OR gate – produces voltage on its output wire if either input wire carries voltage
9


key: chroma:document
string_value:
From Gates to Circuits
basic logic gates can be combined to build more advanced circuitry
example: adding two binary numbers
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)
10


key: chroma:document
string_value:
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)
11


key: chroma:document
string_value:
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
12


key: chroma:document
string_value:
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
13


key: chroma:document
string_value:
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 burst on the Set wire produces output current, which then cycles
14
◼ a current burst on the Reset wire produces no output current


key: chroma:document
string_value:
From Circuits to Microchips
initially, circuits were built by wiring together individual transistors
◼ this did not lend itself to mass production
◼ even simple circuits consisting of 10s or 100s of transistors were quite large
15
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 or chip
◼ since every component is integrated onto the same microchip, these circuits 
became known as integrated circuits
the production of integrated circuits is one of the 
most complex engineering processes in the world
◼ transistors can be as small as 5 nanometers    
(~ 1/16,000th the width of a human hair)
◼ since a hair or dust can damage circuitry, chips 
are created in climate-controlled "clean rooms"


key: chroma:document
string_value:
Manufacturing ICs
16
1. initially, the silicon chip is covered with a semiconductor material, then coated with a layer of 
photoresist (a chemical sensitive to UV light)
2. transistors are then printed onto a mask (transparent surface on which an opaque coating has been 
applied to form patterns)
3. UV light is filtered through the mask, passing through the transparent portions and striking the 
surface of the chip in the specified pattern
4. the photoresist exposed to UV light reacts, hardening the layer of the semiconductor below it
5. 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
6. the process can be repeated 40-60 times depositing multiple layers


key: chroma:document
string_value:
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
17
Moore’s Law describes the 
remarkable evolution of 
manufacturing technology
◼ Moore noted the # of 
transistors on a chip 
doubles every 1-2 years
◼ has held true for 50 years
◼ technology has slowed, but 
the pattern continues to 
hold due to multicore 
processors


key: chroma:document
string_value:
Most impactful inventions
science writer Daniel Stone ranked the 10 most important/impactful inventions
◼ do you agree with his list?
(Daniel Stone. “The 10 Inventions that Changed the World.” National Geographic Magazine, June 2017.)
1
more than any other invention, computer technology is still evolving, which 
means that it continues to impact society in new ways


key: chroma:document
string_value:
Impact on Money
40+ years ago, the U.S. was a cash -based society
2 tech developments changed that
1. cheap, portable devices for processing credit card 
transactions
2. expansion of the Internet
 banks could treat money as numbers in a file
 led to expansion of ATMs, debit cards, online banking
many Americans now live virtually cash -free
▪ in 2019, 39 billion credit card transactions, 10 billion ATM transactions
▪ in 2020, most individuals carried less than $40
cryptocurrencies like Bitcoin are growing in popularity
▪ market-based, not backed by government or bank
▪ offers complete anonymity, potentially tax free
▪ very volatile, not clear if will be widely accepted
2


key: chroma:document
string_value:
Negatives: debt & security
the convenience of ATMs, debit/credit cards has led to a debt crisis for many
◼ avg. credit card interest rate: 16%
◼ by comparison: 30-year mortgage (2.8%), 5-year CD (0.31%)
2021 credit card debt in U.S. totaled $807 billion
◼ avg. household credit-card debt: $6,270
electronic money meant fewer muggings, but introduced identity theft & fraud
◼ nearly half of Americans experienced in 2020, total loss of $712 billion
3


key: chroma:document
string_value:
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 98% of all computer processors
◼ modern homes contain hundreds of embedded processors
 in ovens, television remote controls, cordless phones, automatic thermostats, …
◼ automobiles employ embedded processors to control a wide variety of 
components
4


key: chroma:document
string_value:
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
smart phones and hand -held 
computers have driven the 
development of mobile apps
◼ in June 2021, Apple's App Store listed 
2.2 million apps, Google's Play Store 
listed 3.4 million apps
◼ Amazon's Kindle & Sony's Reader 
enable downloading and reading 
electronic books
5


key: chroma:document
string_value:
Negatives: overreliance
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
◼ from 1985-1987, 4 cancer patients died from radiation overdoses due to a single 
coding error in medical equipment software 
◼ in 1991, 28 soldiers were killed by a Scud missile because a software 
error(involving number roundoff) 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)
◼ in 2010, Toyota recalled more than 400,000 hybrid due to faulty anti-lock brake 
software (estimated cost exceeds $6 billion)
◼ in 2012, Knight Capital group lost $461 million in 30 minutes due to a bug in 
their online trading software


key: chroma:document
string_value:
software (estimated cost exceeds $6 billion)
◼ in 2012, Knight Capital group lost $461 million in 30 minutes due to a bug in 
their online trading software
◼ from 2016-2019, self-driving cars have caused 6 fatalities
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 6


key: chroma:document
string_value:
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/day, can report on breaking stories
◼ text can be integrated with other types of media
◼ the immediacy of online delivery system is especially appealing
independent media organizations have utilized the Web to present stories and 
opinions that might not otherwise reach a mainstream audience
in order to compete, many newspapers/magazines now offer online services
7


key: chroma:document
string_value:
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
8


key: chroma:document
string_value:
Negatives: fake news
the openness of the Web allows for a diversity of views to be presented
◼ but, not all views are fact-based or unbiased
◼ misinformation or disinformation (intentional misinformation) are widespread
Americans rated online misinformation a major problem (2019)
◼ only 26% were very confident in their ability to recognize fake news
9


key: chroma:document
string_value:
Negatives: info overload
the impressive range of information available online can be viewed as a 
strength, but it is also one of the greatest weaknesses
◼ as of 2019, Web estimated in hundreds of billions of pages (maybe much more)
◼ finding specific info can be hard, even with search engines
since most Internet/Web content lacks editorial review, it is up to the user to 
evaluate its credibility
10


key: chroma:document
string_value:
Internet/Web for Communication
many users were originally drawn to the Internet by the availability of 
electronic mail and newsgroups
◼ in 2021, 4.1 billion active email users worldwide (1.8 billion used Gmail)
◼ 319.6 billion email messages were sent/received each day (~50% spam)
increasingly, the Internet is being 
used for social networking
◼ in 2021, 97% of Americans own 
cell phone, 85% own smartphone
◼ 23 billion texts sent in 2020
social media sites have grown in 
popularity
1. Facebook
2. YouTube
3. Whatsapp
4. WeChat
5. Instagram
11


key: chroma:document
string_value:
Negatives: addiction
studies have shown social media can be physically & emotionally addictive
▪ in 2018, average adult spent 6 hours/day on connected devices
▪ assuming 7 hours of sleep, that's 35% of waking day
nomophobia: fear of being detached from mobile phone connectivity
12


key: chroma:document
string_value:
Negatives: cyberbullying
preteen & teen use of social media has led to bullying via text & social media
▪ annual survey in U.K. identifies negative consequences
▪ suicide rate for teen girls in U.S. increased 65% from 2010 -2015, 
coinciding with rise in smartphone social media use
also, texting while driving is 6x more dangerous than drunk driving
13


key: chroma:document
string_value:
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
14


key: chroma:document
string_value:
Internet/Web for Commerce
total online sales in 2020: $861 billion
some of the most successful sites are 
online offshoots of traditional retailers
◼ Walmart, Best Buy, PetSmart
Amazon is by far the dominant force
◼ more than 1/3 of ecommerce sector
15
the Web has provided a new advertising channel for businesses
◼ e-commerce sites charge fees for hosting advertising banners on Web pages
 banner ads are clickable images that promote a company’s product or service
 users who click on the ad are directed to the company’s Web site
◼ the Web’s structure allows for a direct connection between ads and related 
purchasing interfaces


key: chroma:document
string_value:
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)
16
Negatives: privacy


key: chroma:document
string_value:
Negatives: security
email also raises privacy concerns
◼ email messages travel through numerous routers, and each router represents a 
security risk
◼ 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
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
increasing occurrences of phishing attacks, in which people are fooled into 
surrendering sensitive information via email
privacy is closely linked with security
◼ 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
17


key: chroma:document
string_value:
In conclusion…
"Technology is, of course, a double edged sword. Fire can cook our 
food but also burn us." –  Jason Silva
overall, changes brought about by computers have been extremely positive
◼ there is no going back, computers are integrated into our lives
not all change is good, so you need to be informed and diligent about the 
choices you make
◼ social media allows people to connect over distances, but also can lead to 
physical isolation and cyber-bullying
◼ facial recognition can add security to banking, but can invade privacy and be 
discriminatory
hopefully, this book has helped you better understand computer technology 
and its applications
◼ will enable you to make informed choices about how you adopt technology
18


key: chroma:document
string_value:
The Digital Divide
access to computers & Internet/Web offers numerous advantages
▪ education, citizenship, employment, …
a troubling aspect of recent technological developments is that the benefits 
associated with computers are not shared equally by all
1
lower income 
Americans are 
far less likely to 
be online
many rely on 
smartphones for 
access


key: chroma:document
string_value:
The Digital Divide (cont.)
similarly, inequities occur for those with minority ancestry or disabilities
2


key: chroma:document
string_value:
Homework Gap
the Digital Divide was highlighted during the 2020 COVID -19 pandemic
◼ many schools closed and students were transitioned to online classes
◼ those with home computers and reliable Internet were able to interact via 
videoconferencing software & complete online assignments
◼ those without were severely disadvantaged
3


key: chroma:document
string_value:
Addressing Inequities
in late 1990s, U.S. government prioritized Internet connectivity
▪ by 2003, nearly all public schools were connected (vs. 35% in 1994)
▪ most public libraries provide free access to Internet -enabled computers
▪ programs (e.g., Lifeline, Emergency Broadband Benefit) subsidize 
cellular and Internet bills for low -income families
4
numerous not-for-profit organizations address the Digital Divide
▪ National Digital Inclusion Alliance coordinates hundreds of organizations
▪ EveryoneOn connects low-income families with affordable Internet plans 
and devices
▪ Computers for Kids takes old computers, refurbishes them, and donates 
them to schools and needy kids
▪ Boys and Girls Club of America offers educational programs


key: chroma:document
string_value:
The Global Divide
globally, wealthier countries are more likely to have computers/Internet 
the U.N. and World Economic Forum lead numerous initiatives
◼ 2021 Generation Equality Forum raised $40 billion in new investments
many private sector initiatives as well
▪ One Laptop Per Child has donated more than 3 million low-power laptops
5
in 2014, 3 countries 
accounted for half 
of all Internet traffic
1. China (29%)
2. U.S. (13%)
3. Japan(8%)


key: chroma:document
string_value:
Diversity in the Tech Sector
6
tech industry is one of the most dynamic & exciting sectors of the economy 
▪ no other industry has the same potential for rapidly taking ideas and turning 
them into devices/applications that change the world
▪ e.g., cell phones & smartphones widely adopted within 10 years
many applications were the brainchild of a single person or small team
▪ Word Wide Web Tim Berners-Lee, 1990
▪ Mosaic browser Mark Andreesen & Eric Bina, 1994
▪ Google  Larry Page & Sergey Brin, 1998
▪ Facebook  Mark Zuckerberg, 2004
▪ Twitter  Jack Dorsey, 2006
▪ Instagram  Kevin Systrom & Mike Krieger, 2010
all these pioneers/innovators/entrepreneurs are white males
▪ women and people of color have been and continue to be 
underrepresented in the tech industry (especially in leadership)


key: chroma:document
string_value:
Success Stories
7
certainly, there have been successful leaders and innovators
◼ Jerry Lawson (1940-2011): led development of first 
cartridge-based video game, founded VideoSoft in 1980.
◼ Marissa Mayer (1975-): first female engineer at Google, led 
in development of Google Maps, Google Earth & Street Maps. 
CEO of Yahoo! from 2012-2017.
◼ Luis von Ahn (1979-): founded digital security company 
reCAPTCHA. Also founder and CEO of DuoLingo.
◼ Whitney Wolfe Herd (1989-): founded Bumble, youngest 
woman to take her company public on NYSE & youngest 
female self-made billionaire.


key: chroma:document
string_value:
Underrepresentation
in 2020, women were > 50% of U.S. workforce, but only 26% of tech jobs
◼ only 7% of Fortune 500 CEOs were women
even greater underrepresentation for minority groups
◼ Hispanic/Latinx Americans: 18% of workforce, 8% of tech jobs
◼ African Americans: 13% of workforce, 5% of tech jobs
8


key: chroma:document
string_value:
Increasing Diversity
9
tech companies are addressing equity/diversity, but change has been slow
◼ changing company culture to be more inclusive
◼ changing hiring practices to bring in more diversity
◼ creating mentoring programs for women & minority employees
one problem is that stereotypes & misinformation influence people when they 
are young
◼ TV & movies perpetuate white/Asian male sterotypes
◼ access to computers in schools is not equitable
◼ among 2020 college graduates with major in computer science:
 18% were women, 10% were Hispanic/Latinx, 9% were African American
many initiatives are focused on providing access/mentoring for young people
◼ e.g., National Center for Women & Information Technology (NCWIT), AnitaB.org, 
Code.org, Black Girls Code, and Hispanics in Computing
◼ AP CS Principles course launched in 2017, specifically designed to increase 
participation by women and minorities


key: chroma:document
string_value:
Benefits of Diversity
studies have shown numerous benefits of diversity in the workplace
1. companies are more productive when teams are diverse in 
background/perspective
2. different viewpoints & experiences produce a diversity of ideas, which 
can encourage innovation
3. an openness to workers who look and think differently means 
outstanding candidates who might have been overlooked are now 
hired 
4. a diverse workforce is better at understanding and responding to a 
diverse client base
5. the products designed and built by a diverse team tend to be higher 
quality and more equitable
e.g., cell phone interfaces designed by men that are difficult to use by women 
with smaller hands
e.g., 5-year gap between release of Apple emojis and emojis with different 
skin tones
10


key: chroma:document
string_value:
Algorithmic bias
algorithmic bias occurs when faulty assumptions and poor design practices 
lead to software that discriminates
1. in 2015, Amazon announced it was abandoning interview software that was 
proven to discriminate against women candidates
2. in 2016, ProPublica published a report documenting how sentencing software 
used in courts discriminated against minority suspects
3. in 2019, Science published a report documenting how hospital software for 
screening patients discriminated against minority and low-income patients
4. Several studies have confirmed that facial recognition software misidentifies 
women and people of color disproportionally, leading to more arrests due to use 
by law enforcement.
in all these cases, algorithmic bias was not intentional
• lack of diversity led to unquestioned assumptions & flawed development process
11


key: chroma:document
string_value:
Bridging the Divide
when combating any form of discrimination and inequity, awareness is the 
first step
in the past decade, awareness of the Digital Divide has led to change
◼ governments and companies are leading equity efforts
◼ young women and people of color are being encouraged to consider future 
careers in computing
◼ recognition of toxic corporate cultures & unfair hiring practices are producing 
change (albeit slowly)
◼ recognition of the dangers of algorithmic bias is leading to new design and 
testing methodologies
12


