CS 16 – Jan. 12 Definition of computer & CS Making good decisions Computer organization A...

Preview:

Citation preview

CS 16 – Jan. 12

• Definition of computer & CS

• Making good decisions

• Computer organization

• A little history

Computer definition

• An electronic device that can retrieve, store and process data

• You can do these things too!

• What is the difference?

Computer science

• Systematic study of how we …– solve problems – represent & manipulate information

• Computer has large memory and fast “brain” – ideal for testing theories

Good decisions

• Correct (not misleading)

• Relevant

• Significant (don’t play weak cards)

• Complete/thorough– Consider alternatives, suggest future work

• Reasonable– Balance between acceptable & ideal

Computer organization

• Definition gives hint on how a computer is organized…

• Retrieve/store data: computer’s memory

• Process data: the CPU

• Communication is also essential– I/O devices– network

Hardware vs. Software

• CPU

• Memory

• Peripherals

• network

• Helps us interact with the machine

• Gives it soul or behavior

• Translates to/from machine language

CS 16 – Jan. 14

• A little history

• Introduce binary numbers

Before 1940s

• Only analog machines, moving parts

• Specific purpose– Adding machines– Tabulators– Sunrise/sunset, celestial

• General computing only theoretical interest– Alan Turing

1940s

• Code-breaking machines in WW 2

• General purpose electronic computers– ENIAC, U. of Pennsylvania– ABC, Iowa State– Z3, Konrad Zuse in Germany

• Transistor (1947) to have impact later

• von Neumann concept forms basis of computer organization

US Army photo

1950s & 1960s

• Commercially produced computers (IBM)– gradually become more common in industry

• Programming languages developed to facilitate commands to the machine

• Colleges begin to teach computing

• Large and expensive

• Moore’s Law

1970s & 1980s

• Integrated circuit (1971) allows computers to become much smaller– Intel chips 4004, 8008, 8086, 80286, etc.

• Personal (home) computing– Applications for non-specialists

• Intense competition • Internet only used in large companies,

universities

1990s & 2000s

• Computer for communication and mass medium

• Internet as a virtual library & soapbox

• Tech companies (Apple, Microsoft, Intel, Nokia,…) mature and gain clout

• Growing need to manage information

Binary Numbers

• Binary = “base 2”

• The “2” means each bit is either 0 or 1

• To interpret a binary number,

use place value system.

Place value system

• In base 10, what does 278 mean?

• 278 = 2 * 102

+ 7 * 101

+ 8 * 100

• Each digit corresponds to a power of 10

Binary example• So now let’s try base 2: What is 11010?

1 * 24 + 1 * 23 +

0 * 22 +

1 * 21 +

0 * 20

• More concise to simply say24 + 23 + 21

Powers of 2

• 20 = 1

• 21 = 2

• 22 = 4

• 23 = 8

• 24 = 16

• 25 = 32

• 210 ~ 1 thousand

• 220 ~ 1 million

• 230 ~ 1 billion

• 240 ~ 1 trillion

Binary Decimal

• In a binary number, each “1” gives you a power of 2

• More examples:

11

101

110

1110

Questions

• Let’s say we have 4 bits.

• What is the lowest number?

• What is the highest number?

• Try same experiment with 5 bits.

CS 16 – Jan. 16

• Interpreting binary decimal √

• Decimal binary

• Shorthand ways of expressing binary– Octal

– “Hex”

• Negative numbers

Number of Possible Values

• 1 bit: 0 and 1

• 2 bits: 00, 01, 10, 11

• 3 bits: 000, 001, …?

• For a given number of bits, how many patterns?

decimal binary

• You already know binary decimal

• But given a decimal number like 45, what is binary form?

• Binary numbers are longer than decimal.– (Ex. 5 digit number may require 15 bits)

• My technique is the “binary store”

Binary store

• At the Binary Store, price is a power of 2: $1, $2, $4, $8, $16…

• If you had $45, what could you buy?

• 45 = 32 + 8 + 4 + 1

• Write powers of 2: 25 + 23 + 22 + 20

• Write binary number: 101101

Another example

• Let’s convert 61 to binary:

• Go to binary store with $61…

61 = 32 + 16 + 8 + 4 + 1

61 = 25 + 24 + 23 + 22 + 20

Finally: 111101

Octal

• Octal means base 8: each digit is a power of 8.

• Because 8 = 23, each octal digit corresponds to 3 bits

• 4618 = 100 110 0012

• 73258 = ?

Hexadecimal (“hex”)

• Base 16: each digit is a power of 16

• Since 16 = 24, each hex digit corresponds to 4 bits.

• Hex also means we have 16 different digits.

• a = 10, b = 11, c = 12, d = 13, e = 14, f = 15

Hex examples

• 96416 = 1001 0110 01002

• d12316 = 1101 0001 0010 00112

• Now let’s go the other way:

• 1110002 = ______16

• 100111112 = _______16

Decimal octal, hex

• Often the best way to come up with octal or hex is to go thru binary first.

• Ex. What is 71 in octal?– Binary store gives: 71 = 64 + 4 + 2 + 1– Binary number is 1000111

– Grouped as octal: 001 000 1112 = 1078

• We can check answer.

Why couldn’t the computer scientist tell the difference between Halloween (Oct 31) and Christmas (Dec 25) ?

Negatives?

• We can used a “signed” representation.

• We want half the rep’ns to be negative.

• Ex. 5 bits 32 numbers.– 16 numbers are negative– Thus, range is –16 to +15.

• For n bits: range is –2n–1 to 2n – 1 – 1

How to represent negatives

• In ordinary (unsigned) binary, this was impossible!

• In signed: 3 steps to represent –x:

1. Find rep’n of +x.

2. Invert the bits.

3. Add 1.

• Try some examples.

CS 16 – Jan. 21

Chapter 3: data representation• Many kinds of data all in binary• Today: integers

– Unsigned– Signed

• Later: text, images, code, etc.

Different kinds of data!

Kind of data File type Software used

Numbers.xlsx

.accdb

Excel

Access

Text

.txt

.docx

.html

NotePad

MS Word

Dreamweaver

Image .gif Photoshop

Instructions .exe The operating system

Converting to binary

• A computer system has both HW & SW• HW: only understands binary• SW: Translates human information into binary for

the HW.• How?

– Break into pieces (digits, words, letters, symbols, pixels, …)

– Each piece individually gets a binary number.

Data vs. information

• What does 29613 mean to you? Or is it just a random number?

• What might 111010110101110010… mean to the computer?

• Information means that we are adding “meaning” to the data

• Binary is like the alphabet… all languages use it to give meaning to letters. What is “pet set” ?

Analog vs. Digital

• Analog is how WE understand the world

• Just “warmer” or “crooked” is enough for us

• Can handle “in between” values

• Think of a clock, speedometer, odometer

• Digital emphasizes exact values, usually expressed as 0 or 1, true or false.

• No such thing as “in between.” It’s either 10:30 or 10:31…

An analogy

Think of the notes on a piano.• 88 keys• Range: from lowest to highest key.• Granularity: distance between consecutive notes.• But for computer, notes are converted to binary

numbers!

Representations

• To represent anything in binary, need to know:– Number of bits? (size)

– What do the bits mean? (scheme)

• Representation schemes for integers:– unsigned– signed– sign magnitude– BCD

Size of rep’n

• Most often 8, 16, or 32 bits

• For our examples, we’ll use small sizes

• 5 bits: 25 different numbers

• 32 bits: 232 different numbers

Scheme I: Unsigned

• Ordinary binary number. • For 5 bits: smallest = 00000 (zero)

largest = 11111 (31)

• In general, smallest = 0, largest = 2n – 1.

• Going beyond possible range: “overflow”

Scheme II: Signed

• Allows for negative numbers

• We want half the rep’ns to be negative.

• Ex. 5 bits 32 numbers.– 16 numbers are negative– Thus, range is –16 to +15.

• For n bits: range is –2n–1 to 2n – 1 – 1

Review:

How to represent negatives

• In unsigned, impossible!

• In signed: 3 steps to represent –x:– Find rep’n of +x.– Invert the bits.– Add 1.

• Try some examples.

Review:

Closer look at signed

• In 5 bits: largest number is 01111 (+15)

lowest number is 10000 (–16)

• Leftmost bit is “sign bit”

• Positive #’s have same rep’n as unsigned.

• Technique for –x doesn’t work for –16.

Recap example

• What does 110010 represent if interpreted as:– 6 bit unsigned?– 6 bit signed?

Scheme III: Sign-magnitude

• Leftmost bit works like a +/- sign.• Remaining bits behave like unsigned.

• Example: what is 11001 ?– Leftmost bit “1” means number is negative– Remaining bits are 1001 = 9, so entire number is –9

• What would –20 look like in 8 bits?– +20 looks like 10100 or 00010100– To make it negative, change first bit to 1.

Scheme IV: BCD

• “Binary Coded Decimal”– Only good for positives.

– Each decimal digit corresponds to 4 bits.

– Easy conversion for binary decimal

• Ex. 278 = 0010 0111 1000

• If we have 8 bit BCD, what is the range?• Waste

Having enough bits

• Question – Are 6 bits sufficient to represent the number 50?

• Answer – Depends on the rep’n scheme. Let’s look at each one.

CS 16 – Lab #2

Excel– values and formulas– Awesome number cruncher– Slick functions: sort, subtotals, charts– Can help answer probing questions

• White pages = reading• Yellow pages = lab

• Only one thing I don’t like about Excel…

Bill Gates – Microsoft

Spreadsheets

• Looks like graph paper

• Cells, rows, columns, pages (worksheets)

• Each cell has a name, like E3.

• Into each cell you may type either:– value – formula

How we use Excel

• Enter data

• Ask Excel to calculate formulas

• Insert more data: Excel recalculates.

• Look for trends, conclusions

• Can format to make look professional.

Excel 2007

• New version: different appearance from before• File names now end in .xlsx instead of .xls

– If you find an older version spreadsheet, can “save as” new version.

• New features– Can support larger spreadsheets

– Smaller file size – (More options for presenting data, formatting) …

Chapter 1

• Entering text & formulas

• Navigating a spreadsheet– Workbook, worksheet, rows, columns

• Adjusting row & column width

• Adding/deleting rows & columns

Examples

• Keeping track of calories for a week– Total calories per day– Average calories per meal

• The cost of going to college– How fast is cost rising?– What share is tuition?

• Grade sheet: formulas

Spreadsheet data

What can you put in a cell?• Value: text label or a numerical value• Formula

– Ex. =b1 + b2 + b3 + b4– Ex. =sum(b1:b4)

– Excel functions are very convenient! We’ll use about 10-20 of them.

Hints for formulas

• Use cell ranges, like B3:C7

• Absolute reference– Won’t change when formula copied/moved– Signify with $, as in $E$9– Ex. Calculate a percent share.– Helps avoid “magic numbers”.

Functions

What kinds of functions can Excel do?

• Arithmetic (average, count, sum, …)• Logical (if, countif, sumif, and, or, …)• Statistical – variance, normal curve, …• Financial – interest, loans, annuities, …

• And more!

Ready for lab?

• Best to read white pages before lab – explains the details.

• Peek at end of “hands-on exercise” to see what spreadsheet will eventually look like.

• Copy entire Exploring Excel folder to your memory stick

CS 16 – Jan. 23

Number representation• Integer

– Unsigned √– Signed √– Sign-magnitude – BCD

• Real– Convert from decimal to binary

– Binary scientific notation

Scheme III: Sign-magnitude

• Leftmost bit works like a +/- sign.• Remaining bits behave like unsigned.

• Example: what is 11001 ?– Leftmost bit “1” means number is negative– Remaining bits are 1001 = 9, so entire number is –9

• What would –20 look like in 8 bits?– +20 looks like 10100 or 00010100– To make it negative, change first bit to 1.

Scheme IV: BCD

• “Binary Coded Decimal”– Only good for positives.

– Each decimal digit corresponds to 4 bits.

– Easy conversion for binary decimal

• Ex. 278 = 0010 0111 1000

• If we have 8 bit BCD, what is the range?• Waste

Having enough bits

• Question – Are 6 bits sufficient to represent the number 50?

• Answer – Depends on the rep’n scheme. Let’s look at each one.

Integer vs. Real

• Integer arithmetic on computer is quick and exact, but limited range

• Real arithmetic needs wide range, reasonable degree of precision– Preferred for numerical computation– 14 significant digits is usually enough!

Binary examples

Look at this sequence:

111 = 7

1110 = 14

11100 = 28

111000 = 56

1110000 = 112

• Let’s go the other way

111. = 7

11.1 = 3.5 or 7/2

1.11 = 1.75 or 7/4

.111 = 7/8

.0111 = 7/16

Another example

10100 = 20

1010 = 10

101 = 5

10.1 = 2.5 or 5/2

1.01 = 1.25 or 5/4

.101 = 5/8

Each digit corresponds to (+/–) power of 2.

Convert to binary

• Separate number (e.g. 5.7) into integer and fractional parts.

• Integer part? Binary store.

• Fractional part:– Keep multiplying fractional part by 2 until it

becomes zero, or until you have a repeating pattern.

Example

Convert 9.625 to binary.• “9” becomes 1001.• Fractional part is 0.625:

.625 * 2 = 1.25

.25 * 2 = 0.5

.5 * 2 = 1.0

Fractional part reached 0. So answer is 1001.101

Example

Let’s convert 4.6875 to binary

The “4” becomes 100.

Fractional part is 0.6875:

.6875 * 2 = 1.375

.375 * 2 = 0.75

.75 * 2 = 1.5

.5 * 2 = 1.0

Fractional part reached 0. So answer is 100.1011

Repeating pattern

• Let’s try converting 0.7 to binary.

.7 * 2 = 1.4

.4 * 2 = 0.8

.8 * 2 = 1.6

.6 * 2 = 1.2

.2 * 2 = 0.4

And we’ve seen “.4” already. ____

Answer is .1 0110 0110 0110 … or .10110

CS 16 – Jan. 26

• Finish real numbers• Representing information

Not just in binary, it has to be organized:– Linear

– Non-linear• Network: graph

• Hierarchy: tree

• Representing text– ASCII and Unicode

Real-number rep’n

• Also called “Floating-point”• Size is 32 or 64 bits.• Based on “binary scientific notation”• Only one scheme is used:

1 bit for sign 8 bits for exponent 23 bits for mantissa

• Big mantissa precision

Distribution

• 8 bit exponent 256 different exponents– Biggest number ~ 1038.– Smallest (+) number ~ 10–38.

• 23 bit mantissa 8 million numbers per power of 2.

• Three kinds of numbers can’t be represented. (Where are they?)

Linear organization

• Definite begin & end• One logical way to read (forwards)• Used for: text, audio, images, video

• One file consists of many “cells” of data– Individual character, musical note, pixel on screen,

frame of movie

– It’s convenient if each “cell” is a whole number of bytes. 1 byte = 8 bits.

Digitizing data

• Text– Break up information into characters

– Each character represented by a binary number

– How many different binary numbers will we need?

– Need to encode formatting commands as well. E.g. some text may be in a different font.

• Music/audio– Can break up song into notes

– What information is in a “note” ?

– How frequently do notes come? Sampling

Digitizing data (2)

• Images– Break up picture into pixels, each becomes a number.

– How many pixels do we need?

– The pixel values are colors. How many different colors do we want?

• Video– A sequence of images. – How many images per second?

– (Also need to include sound on the side.)

Non-linear organization

• Either there’s no logical begin/end to information, or many ways to travel thru it.

Graph (network) Tree (hierarchy)

Tree example

• We use trees to represent mathematical expressions. There’s a hierarchy because of the order of operations.

*

+ –

3 4 7 8

Representing a tree

• Normally we’d write

(3 + 4) * (7 – 8)

• More efficient to use “postfix” or RPN notation:

3 4 + 7 8 – *

*

+ –

3 4 7 8

CS 16 – Jan. 28

• Text representation• Compression techniques

• Image representation– grayscale

– File size issues

– (Later, we’ll look at color)

The joy of text

• ASCII code:– Contiguous (makes it easy to alphabetize)– Case sensitive– One byte per character

• ASCII table (p. 67)– ‘A’ = 65 ‘a’ = 97 ‘0’ = 48– Try this example: “Dog”

Unicode

• An extension of ASCII• Incorporated into the Java language.• Uses 16 bits instead of 8.

• Supports foreign alphabets; symbols

(examples on p. 68)

Text Compression

• Goal is for a document to take up less space.• Techniques

– Keyword encoding: replace common words by special symbols like δ ↕ ╞

– Run-length encoding: replace repetitions with a number: “pppppppppppppp” [14p]

Also works well for compressing images, sound.

– Huffman code: common letters should take up fewer bits.

Huffman code example

• Suppose you want to send a message and you know the only letters you need are A,D,E,L,N,P,S.

• Try this code:

A D E L N P S

001 100 01 101 0001 0000 11

How to create code

• In CS we often use “trees” to help us solve problems.

• We’re given set of letters used in message, and their frequencies.– Ex. A=5, B=10, C=20, D=25, E=30– Ex. P=5, N=10, D=10, L=15, A=20, S=20, E=30

• Arrange frequencies in order• Group the letters in pairs, always looking for the

smallest sum of frequences Create a tree!

CS 16 – Lab #3

Excel

• Review: values, formulas, functions

• Absolute and mixed references

• Creating Charts

Functions in Excel

• =sum(a1:a4) better than =a1+a2+a3+a4

• Function menu– Can fill in the blanks step by step

• Example – loan payment– Use “pmt” function– Takes 3 parameters, but too much to remember

Absolute references

• Purpose– For constants in a formula– When you don’t want a cell reference to change

when the formula gets copied

• Use “$” as in $E$3 (instead of just E3)

• Examples– Percent of total, sales tax.– Multiplication table (mixed ref.)

Mixed references

• Sometimes used when you want to copy a row or column full of formulas

• $B7 – When we copy, only row # changes.

• B$7 – When we copy, only col # changes.

• Let’s look again at calorie example.

Some stat functions

• Count – # of cells containing numbers

• Counta – # of cells with numbers or text• Countif – number of cells satisfying a

condition you specify (useful in a game!)

• Max and Min

The if function

• Takes 3 parameters:– Question or condition to test– Value if true– Value if false

• Ex. =if(E3 < 65, “Heat”, “A/C”)

• Ex. =if(D8 > 0, D7 / D8, “”)

• Let’s look at climate-data example

vlookup function

• Shortcut for doing lots of if’s in a row.• Ex. Grading scale

=if (B7 >= 90, “A”, if (B7 >= 80, “B”, if (B7 >= 70, “C”, if (B7 >= 60, “D”, “F”))))

• Better approach:– Write grading scale into spreadsheet– Use vlookup to “look up” the right grade.

Tic-Tac-Toe in Excel

• Goals:– Keep track of whose turn it is– Need to know if game over

• Strategy:– Use +1 for ‘X’ and –1 for ‘O’– Sum of board tells whose turn it is– Sum of row/col/diagonal can find winner.

Charts

• Excel creates a chart based on numbers in spreadsheet.

• Updated automatically when you change numbers.

• To create:– Select data (and labels)– InsertChart

Steps to creating chart

• What data do you want in chart?

• Make choices about the chart:– What kind of chart? (column, pie, X-Y, ...)– Format of chart (title, legend, colors, ...)– Where do you want chart?

• When done, can paste chart to another document.

Chart examples

• Furman cost

• Calorie … 3-D

• Size of houses by state

• Big chart: maybe need to adjust scale

• *** Often a good idea to sort data.

CS 16 – Jan. 30

• Image representation– B/W and color schemes

– File size issues

Images

• Fundamental unit is pixel

• Size = usually 8 bits

• Scheme = grayscale, range 0-255

• Dimensions given as (horiz vert)

– Ex. 400 300 120,000 pixels

– Note that an 8-bit pixel = 1 byte

• Aspect ratio

– Ex. 4 to 3

– When changing size, ratio shouldn’t change

Properties of rep’n

• “Sampling & Quantizing”

• Resolution of image– total number of pixels in image

• Dynamic range– How many shades of gray

• To reduce file size– Reduce either # of pixels, or # bits/pixel

Resolution

• here is a (edited) digitized image with a resolution of 272 x 416

Picture resolution determines both the amount of detail as well as its storage requirements

Resolution

• notice the changes when the resolution is reduced (136 x 208)

Picture resolution determines both the amount of detail as well as its storage requirements

Resolution

• notice more changes when the resolution is reduced (68 x 104)

Picture resolution determines both the amount of detail as well as its storage requirements

Dynamic Range

• Here is an intensity or graylevel image with 256 levels (i.e., 0 to 255 scale)

DYNAMIC RANGE refers the number of values for the measuring scale used in quantizing

Dynamic Range

• Here is an intensity or graylevel image with 16 levels (i.e., 0 to 15 scale)

DYNAMIC RANGE refers the number of values for the measuring scale used in quantizing

Dynamic Range

• Here is an intensity or graylevel image with 4 levels (i.e., 0 to 3 scale)

DYNAMIC RANGE refers the number of values for the measuring scale used in quantizing

Dynamic Range

• Here is an intensity or graylevel image with 2 levels (i.e., 0 to 1 scale or a binary image)

• Dithering can help

DYNAMIC RANGE refers the number of values for the measuring scale used in quantizing

Don’t overdo it

• Too little resolution: pixelated

• Too few bits per pixel: sharp edges, cheap– Extreme case is “binary image”

• Note that n bits per pixel gives 2n values in dynamic range. 0 is black, 2n – 1 is white– Examples: n = 8, 4, 2, 1

B/W vs. Color

• B/W: usually 1 byte (8 bits) per pixel– Each pixel = grayscale number 0-255– Ex. 180 is a brighter shade of gray

• Color: usually 3 bytes (24 bits) per pixel– Each pixel has three values, each 0-255– Ex. (200, 50, 128) = ?

Color rep’ns

• RGB – system based on light

• CMY – based on printing

• HSB – based on art

• Indexed color – a swatch to save space

RGB system

• Based on primary colors for light

• Each pixel has (red, green, blue) values.

• Examplesblack = (0, 0, 0)

purple = (75, 0, 100)

white = (255, 255, 255)

• How about (x, x, x) or (0, 0, x) ?

RGB examplesColor R G B

black 0 0 0

white 255 255 255

red 255 0 0

green 0 255 0

blue 0 0 255

cyan 0 255 255

magenta 255 0 255

yellow 255 255 0

CMY system

• Based on primary colors of printing

• Each pixel has (cyan, magenta, yellow) values

• In contrast to RGB:white = (0, 0, 0)

black = (255, 255, 255)

CMY examplesColor C M Y

white 0 0 0

black 255 255 255

cyan 255 0 0

magenta 0 255 0

yellow 0 0 255

red 0 255 255

green 255 0 255

blue 255 255 0

Practical notes

• Printout may look different to screen

• Ex. RGB blue = (0, 0, 255)

but CMY blue = (255, 255, 0)

In other words, in color printer, 2 different toners required to produce blue.

• CMY, a.k.a. CMYK

CS 16 – Feb. 2

• Finish color representation– RGB √

– CMY √

– HSB

– Indexed color

• Chapter 4 – how computers think– Begin with basic building blocks

HSB system

• From artistic standpoint, neither RGB nor CMY makes much sense to people

• More intuitive color definition:– Hue = what color you want– Saturation = how much of that color– Brightness

HSB geometry• Hue = which direction

on color wheel

• Saturation = how far from center

• Brightness = how far up or down

hue

saturation

brightness

Trade-off between saturation and

brightness

Indexed color

• Do we really need 16,777,216 colors?– ~ 200 is more practical

• Indexed color is like RGB:– 6 values of each primary color, not 256– Hex values: 00, 33, 66, 99, cc, ff

• 1 byte per pixel instead of 3

• Dithering to simulate in-between colors

Chapter 4

Begin chapter on computer organization

• Logic gates– Used to perform math operations

• Later: finite automata– basic model of computation

Logic Gates

• Basic building blocks• Usually 2 inputs• X, Y could be 0 or 1.

1 = true0 = false

• By combining 2+ gates, you get more sophisticated functions

‘AND’ and ‘OR’

AND

X Y ans

1 1 1

1 0 0

0 1 0

0 0 0

OR

X Y ans

1 1 1

1 0 1

0 1 1

0 0 0

Adder

• We can teach the computer how to add using just a few logic gates.

• However, we need to look at one more gate, the XOR.

Exclusive or (XOR)

• XOR basically says “either, but not both”

• The output is 1 if both inputs are different.

XOR

X Y Ans

1 1 0

1 0 1

0 1 1

0 0 0

Adder

• Here is the logic to add, one bit at a time.

CS 16 – Feb. 4

• How computers think– Turing machine model

– Finite state machine model

a.k.a. “Finite automaton”

• But first…. Concept of state

State

• Fundamental concept for any computation– Machine keeps track of where it is, what it needs

– a.k.a. Status, mode

– state may be stored in some memory cell

• Many examples– Logging in

– Using a dialog box, or other user-interface

– Fax machine, photocopier, telephone

– Car transmission

Examples

• In a Tic-Tac-Toe game, the “state” of the game would include:– Whose turn it is

– Is the game over? Who won, or was it a tie?

State is determined by looking at the board.

• Backgammon (roll dice, move pieces…)– Depending on your situation in the game, some moves

are illegal.

• Another way to think about states is to consider all possible board configurations!

Turing machine

• Alan Turing, 1936• Any general purpose machine must:

– Work automatically

– Be aware of what state it’s in

– Have sufficient memory

– Be able to do I/O, and be able to read the input many times if necessary

• Powerful model, but tedious to work with

Adder example

• 4 possible states, depending on the inputs– For example, (S = 0 and C = 0) would be one outcome.

• Programming the details make working with real TMs a headache.

x

y

z

S

C

Finite Automatasingular: finite automaton

• Simple model for machine behavior.• Purpose is to accept or reject some input

– Examples: logging in, using a wizard, game

• At any given time, machine is in some “state”– Start state

– Final (or accept, “happy”) states

– Dead states

• Transitions between states

Example

• Vending machine for 25¢ item.

0 5 10

152025

+5 +5

+5

+5+5

+10+10+25

CS 16 – Lab #4

Useful spreadsheet operations

– Chart– Sort– Filter– Subtotals and Pivot tables– Conditional formatting

Tic-Tac-Toe in Excel

• Goals:– Keep track of whose turn it is– Need to know if game over

• Strategy:– Use +1 for ‘X’ and –1 for ‘O’– Sum of board tells whose turn it is– Sum of row/col/diagonal can find winner.

Charts

• Excel creates a chart based on numbers in spreadsheet.

• Updated automatically when you change numbers.

• To create:– Select data (and labels)– InsertChart

Steps to creating chart

• What data do you want in chart?

• Make choices about the chart:– What kind of chart? (column, pie, X-Y, ...)– Format of chart (title, legend, colors, ...)– Where do you want chart?

• When done, can paste chart to another document.

Chart examples

• Furman cost

• Calorie … 3-D

• Size of houses by state

• Big chart: maybe need to adjust scale

• *** Often a good idea to sort data.

Sorting

• Can sort by any column(s).

• Ascending or descending.

• Multiple-column sort to break ties

• Ex. How to sort a list of schools?

A note on sorting

• Sometimes we sort to find the “highest concentration”

• What should we sort by?– values– percentage– surplus / excess

Filtering

• Use filter when you only want to see certain rows.– Ex. Just show me the high schools.

• Can base a filter on – Comparison– Top 10, bottom 10, etc.– 2+ criteria

• Tip: Copy result to another page!

Subtotals

• After sorting, often useful to find subtotal

• Summary function usually “sum”– Ex. School enrollment subtotaled by district.

• Tip: Copy subtotals to another page.

• Trick is to use:

HomeEditingFind&SelectGo To

CS 16 – Feb. 6

• How computers think (continued)

– Finite state machine model

a.k.a. “Finite automaton”

– Representing accepted input as a regular expression

Binary example

• We want a “word” starting with “101…”

need101

need01

need1

1 0 1

01

0 0,1

Binary Example (2)

• We want a word with at least two 0’s.

needtwo

needone

0 0

1 1 0,1

• What if we wanted exactly two 0’s?

What does this FA do?

A B

1

1 00

Regular language

• Any language that can be “accepted” or recognized by a FA.– Credit card numbers

– Social security numbers

– Phone numbers

– Date / Time (e.g. to enter into reservation system)

• Some FAs are too big to draw, so instead we describe with regular expression.– Shows general format of the input

Regular expression

• The key is to use “wild cards” to make a general expression.

• ? = can replace any single character• * = can replace any number of characters• [ ] = can hold a range of possible valid characters

• Examples101* = anything starting with 101

Sep??.ppt = file names like sep25.ppt or sep04.ppt

furman*.xlsx = any spreadsheet about Furman

CS 16 – Feb. 9

Chapter 5• CPU and memory

– Carry out instructions from software.

• John von Neumann’s ideas– Keep program stored in memory

– How to execute each instruction routinely

• Performance

Instruction execution

CPU is workhorse – memory holds program

• Fetch instruction from memory (to CPU)

• Decode – figure out what kind of inst.

• Execute – do it

• And then go on to next instruction

Performance units

Time (clock period) Speed (clock rate)

Second 1 sec Hertz (Hz) 1 Hz

Millisecond (ms) 10-3 sec Kilohertz (KHz) 103 Hz

Microsecond (μs) 10-6 sec Megahertz (MHz) 106 Hz

Nanosecond (ns) 10-9 sec Gigahertz (GHz) 109 Hz

Performance

• Execution time. Need to know:– # instructions that execute– Clock cycles per instruction (CPI)– Clock rate (cycles per second)

• Formula:

sec/

)/(*)(#

cycles

instcyclesinsttime

Example

• How long will a program take to run if it executes 1 million instructions, the CPI is 4 cycles per inst., and the clock rate is 1 GHz?

sec/10

)/4(*)10(9

6

cycles

instcyclesinsttime

mstime 4sec10*4 3

Improving performance

• To reduce time, we can:– Run fewer instructions– Take less time for each instruction– Faster clock We’ll look at this

• Marketing can cheat!

sec/

)/(*)(#

cycles

instcyclesinsttime

• How many cycles to execute 7 instructions?

Cycle F D X

1 1

2 1

3 1

4 2

5 2

6 2

7 3

8 3

9 3

Videos

Please watch these excellent videos from www.uctv.tv

• “Claude Shannon – Father of the Information Age”• “Gordon Moore: Behind the Ubiquitous Microchip”

CS 16 – Feb. 11

Continue Chapter 5• Review of pipelined instruction execution

• Memory system– Limited memory on chip

– Main memory (RAM)

– Secondary memory (e.g. disk)

Cycle F D X

1 1

2 2 1

3 3 2 1

4 4 3 2

5 5 4 3

6 6 5 4

7 7 6 5

8 7 6

9 7

Better approach:• Technique is called

“Pipelining”

• On each cycle, try to do several jobs at once.

• Like an assembly line.

Pipelining the CPU

• CPU consists of parts: fetcher, decoder, executor, etc.

• Without pipelining,

total cycles = (# inst) * (CPI)

• With pipelining,

total cycles = ? (Hint: do first instruction; then handle the rest)

Example

• How many cycles are needed to execute 50 instructions, given that the CPU uses 4 stages? [Fetch, decode, execute, writeback]

4 cycles for the first instruction1 cycle for each of the rest4 + (50 – 1) = 53 cycles

• CPI = 53 cycles / 50 instructions = 1.06

Stalls• What if instruction 2 needs more time?

During cycle 5, instruction 3 has to wait.

Cycle F D X W

1 1

2 2 1

3 2 1

4 2 1

5 2

6 2

Cycle F D X W

1 1

2 2 1

3 3 2 1

4 4 3 2 1

5 4 3 2

6 4 3 2

7 5 4 3 2

8 5 4 3

9 5 4

10 5

Deli pipeline!

• Five stages in deli to make sandwich:– Place order– Get right bread and slice– Put meat on bread– Add condiments– Cashier and pickup.

• What are some possible stalls?

Summary

• Time = total cycles / clock rate

• Is machine is pipelined?– If no, cycles = (# instructions) * (CPI)– If yes, cycles = # stages + # inst – 1 + stalls

• Simultaneous stalls

• With pipelining, CPI is almost 1. – Can we do better than this?

Memory system

• After the CPU, next most important feature

• CPU contains registers – only enough for immediate calculations

• Main memory – running programs

• Secondary memory – long-term storage– “open” vs. “save”

Main memory

• Runs on electricity: “volatile” but fast

• Principle of random access

• Examples:– RAM (vast majority of main memory is here)– Cache (small version of RAM, much faster)– BIOS (“Basic I/O System”)

Secondary memory

• Non-electric, “non-volatile” technologies– Magnetic– Optical

• How to find information? It may be:– Random access (e.g. flash memory; stick)– Direct access (disk)– Sequential access (tape)

Example comparison

Type Size Access time

Cost per MB

CPU regs 256 bytes 1 ns Forget it.

Cache 16 KB 2 ns $ 20

RAM 128 MB 20 ns $ 1

disk 100 GB 100,000 ns $ .001

CS 16 – Lab #5

Excel Chapter 5

• Subtotals & Pivot tables

• Alternate file types

• Converting from text file

• Conditional formatting

• Text functions

Subtotals

• After sorting, often useful to find subtotal

• Summary function usually “sum”– Ex. School enrollment subtotaled by district.

• Tip: Copy subtotals to another page.

• Trick is to use:

HomeEditingFind&SelectGo To

Pivot Tables

• Perhaps most important feature of Excel!• It’s a 2-D subtotal

– Find average salary by job & location– Find total population by state & age– How many colleges in each state by type

• Allows you to discover subtleties– How does tuition relate to size of school?– Is there relationship bet. sugar & caffeine?

Making pivot table

• First, look for 2 columns that may have relationship.

• May need to create vlookup table(s).• No blank rows/columns• InsertPivot Table

– Select data. (default is usually correct)– Put on new page.– Fun to use (just drag…)

Downloading

• Different file types (and sizes)– xls and xlsx– csv (comma separated values)– txt– zip

• Need to clean up file, because someone else wrote it.

Import text wizard

• For converting .txt to .xls

• Need to tell Excel where columns are:– Delimited by spaces, comma, etc.

or– Specific width (# characters)

• Mistake at this stage is costly (can’t undo).

Excel’s text functions

• Excel can do more than numbers.

• Text functions extract part of string:– left( ), right( ), mid( )– search(): find where something is in a string

• Ex. Processing win/loss records

• Ex. Separating first & last names.

Examples

Suppose d7 = “(305)555-8050”=search(d7, “)”) would return 5

=left(d7,5) would return “(305)”

=right(d7, 5) would return “-8050”

=mid(d7, 6, 3) would return “555”

In a spreadsheet, we may want to filter phone numbers by area code

CS 16 – Feb. 13

• Examples of secondary storage

– Disk (direct access)• Various types

• Disk geometry

– Flash memory (random access)– Tape (sequential access)

Disk examples

• Hard drive– Can’t take out. Don’t confuse with RAM

• Floppy disk– 8” , 5 ¼”, 3 ½”

Disk examples

• ZIP disk, “super” disk

• CD (including: CD-ROM, CD-R, CD-RW)– “ROM” = read-only– “R” = recordable– “RW” = read/write

• DVD

Disk geometry

• Tracks

• Sectors

• Platters

Access time

• Seek time – wait to find right track (~ 8 ms)– Head moves at 50 mph!

• Latency – wait to rotate (~ 4 ms)– Based on 7200 RPM

• Transfer – grab data from track

Example: the CD

• Each track has lands and pits.

• 700 MB total, including overhead

• About 25,000 tracks

• About 50 sectors per track

• One bit = about 1.6 microns long,

0.7 microns wide

CD speed

• Nominal speed is 80 mins (150 KB/sec)

• Ex. 12x speed, ~ 7 mins (1.7 MB/sec)

• By comparison, a floppy takes about

100 times slower: (1 MB/min)

• Fragmentation can ruin time!

Flash memory

• Stores electric charge w/o need for electricity

• Usually faster than disk, but varies:• For one KB:

– 0.065 ms to read– 1.5 ms to write

• Thus, per second:– 15 MB/sec to read– 0.6 MB/sec to write

Magnetic Tape

• Compact, about size of microcassette

• Typical capacity 8 GB– Has horizontal tracks

• Takes about 4 hours to “wind”(similar speed to magnetic disk)

• Used for routine/automatic backups

Experiment

How long does it take to move a 20 MB file?

Media Write to Read from

Zip disk 3:00 0:20

CD-RW 2:00 0:20

Flash 0:14 0:02

RAM 0:01 0:01

LAN server 0:04 0:04

External drive 0:03 0:02

CS 16 – Feb. 16

Computer problem solving

Chapter 6: read pp. 148-174

• Problem-solving procedure

• Structure of a solution

• Examples!

Review: what is CS ?• The study of how we …

– Solve problems

– Represent information

• In problem solving, we’d like:– Find systematic ways of going about solution

– Correct, quick and informative solutions.

• Information can be:– Different types: numbers, text, images, sound, the software

itself

– The input and output to a computer program

Why create software?

• Computational power– Excel is limited to so many rows/columns

– Can convert data to images

– Can create games and useful applications

– With one “language”, can solve virtually any problem.

• Built-in features of languages– Many common calculations are pre-defined for you

such as sorting, opening files, surfing the Web, creating a button, etc.

Software• Powerful!

– We get to tell the machine exactly what we want.

– Sometimes, existing programs like Excel or Photoshop are not enough.

• Program = sequence of instructions for CPU to obey.– Works like a recipe.

– A recipe has: ingredients, steps, and result is food!

– A program has: input, calculations, output. When we start to look at programs, be on the lookout for these 3 parts.

Recipes

• Cooking may be a good analogy, because it’s solving a specific problem “I’m hungry.”

• What do we see in recipes? Here’s one:– Brown the beef 15 min. Drain grease.

– Dice carrot, celery, onion (aka “mirepoix”)

– Cut up and boil 6 potatoes until soft.

– Mash potatoes

– Add flour, spices, sauce, mirepoix to beef.

– Put meat mixture into casserole, top with potatoes.

– Bake in oven at 400 for 30 minutes.

Recipes (2)

• A computer program has some of the same elements as a recipe…

• In recipes we see:– Ingredients (the “nouns” of the problem)

– Steps to perform (the “verbs”)

– In some steps, we continue/wait for something

– Although it’s not obvious, sometimes we check things:• Are potatoes fully mashed?

• Should I add more _____ to the mixture?

Recipes (3)• But we don’t eat the same stuff every day. Once we

know a few recipes, we can put together a menu for choices.

if (have all ingredients), make Shepherd’s pie.

if (no potatoes), just make soup instead.

if (no veggies), make hamburger.

if (no beef), make pasta.

• When you view a whole menu as a program, then “making soup” becomes a sub-program.– A large program is composed of several parts.

– In industry, sometimes each part implemented by different people. A kitchen may have many chefs.

Problem-solving

1. Understand problem; inputs and outputs

2. Write solution in English “pseudocode”

3. Write code in a programming language

4. Compile

5. Run and test

• When program works, can refine.

Problems• The earliest problems given to a computer were

mathematical.• Sometimes there is no clean formula

– Many equations can’t be solved analytically. For example, cos(x) = x. Need to solve numerically.

– Ex. Heat equation is a partial differential equation (PDE). Most PDEs have to be solved numerically.

– Ex. Calculating a square root.

• And even if there is a clean formula, a computer can help you automate the calculations.

Problems (2)• “Mathematical” problems may at first sound boring.

But they include many useful applications– Ex. Finding directions

• Other kinds of problems for the computer– Games

– Record keeping, managing investments, …

– Networking, communication

– Multimedia (e.g. image processing)

– Of course, much more!

CS 16 – Feb. 18

• Solving simple problems: create algorithm• Structure of solution

– Sequence of steps (1,2,3….)

– Sometimes we need to make a choice

– Sometimes we need to repeat some steps

• Examples

• Computer science is a problem-solving discipline.

• Every solution (program) should have a well-defined structure, such as listing the ingredients and steps for input, calculations and output.

Example problems

• How would you solve these problems?– Print the numbers from 1 to 10.– Searching for something.

• In this list (3, 2, 7, 5, 4) where is the number 5?• Which room contains my umbrella?

– Play Tic-Tac-Toe.

• Idea for solution (algorithm) is more important than typing code at the keyboard.

Computer program

• Sequence of instructions that machine carries out

• Nouns and verbs

• Structure:– Input, calculations, output– Auxiliary functions

Kinds of statements

• Get input

• Print output

• Assign value to variable

• If-else

• Loop

CS 16 – Lab #6

• Downloading spreadsheets– Various formats; web query

• Text functions (e.g. win-loss record)

• Decision-Making– Scenarios

– Goal seek

– Solver

Work on chapter 8

Downloading

• Different file types (and sizes)– xls and xlsx– csv (comma separated values)– txt– zip

• Need to clean up file, because someone else wrote it.

Import text wizard

• For converting .txt to .xls

• Need to tell Excel where columns are:– Delimited by spaces, comma, etc.

or– Specific width (# characters)

• Mistake at this stage is costly (can’t undo).

Excel’s text functions

• Excel can do more than numbers.

• Text functions extract part of string:– left( ), right( ), mid( )– search(): find where something is in a string

• Ex. Processing win/loss records

• Ex. Separating first & last names.

Examples

Suppose d7 = “(305)555-8050”=search(d7, “)”) would return 5

=left(d7,5) would return “(305)”

=right(d7, 5) would return “-8050”

=mid(d7, 6, 3) would return “555”

In a spreadsheet, we may want to filter phone numbers by area code

Web Queries

• Very often, we want to manipulate data we find on the Web.

• Excel can grab a table from a Web page and convert it to a spreadsheet!

• Data Get External Data From Web

Scenario Manager

• Allows you to change several cells at once

• Scenario summary: see all scenarios.

• Ex. We can look at “grade” demo again.

Goal Seek

• I want a $500 payment.

• Goal seek can find the input loan amount.

Solver

• Similar to Goal Seek, but multiple input cells

• Example: a factory that makes cookies needs to produce just the right mixture of cookies to maximize profit.– Constrained by supplies of raw materials.

CS 16 – Feb. 20

• Solving simple problems: create algorithm

• What does a solution look like?

• Examples

Algorithm

• Clear sequence of steps to arrive at a solution to a problem. Must specify:– Input, output, variables and operations used

– The order in which the steps are taken

• Ideally, each step should perform one calculation:– Input or output of one value

– One calculation, or decision to make

– Calculations usually limited to basic math

– Tedious details can be put off until later.

Examples

• Algorithm to add two numbers– Ask the user to enter 2 values– Obtain the input, and call the values a and b.– Set a new variable sum and set it to: sum = a + b.– Output sum.

• Calculate weekly wage. √– Get hours and rate from the user.– Set the wage as follows:

• If (hours > 40), use overtime formula• Otherwise, use regular formula

– Output wage

Structure

Steps can be hierarchical (nested):

for (day = 1 to 365)

if (Saturday or Sunday)

stay home

else

1. eat breakfast

2. for (hour = 8 to 16.30)

work

3. eat dinner

Loop example

• Add up the numbers from 1 to 5– No input!– Need 2 variables: sum and counter.

• The counter variable will go from 1 to 5, one at a time.• The sum will start at 0, and we will continually add to the sum.

– Sum = 0 and counter = 1– For each value of counter from 1 to 5:

• Sum = sum + counter

– Output sum

• If we can add 1-5, we can just as easily add 1-1000!

Mystery

• What does this algorithm do?– No input.– Create two variables: sum and counter.

Start sum = 0 and counter = 1– For each value of counter from 1 to 20:

• Introduce new variable called temptemp = counter * counter

• Sum = sum + temp

– Output the sum

CS 16 – Feb. 23

The Joy of Text

• Software for text– Text formatters vs. word processors

• Spell checking

Text Software

• Text editor (Notepad, Wordpad, emacs, vi)

• (Web) Browser (Netscape, Opera)

• Text formatter (LaTeX, Groff)

• Word processor (MS Word)

example.html

browser

See on screen

example.tex

LaTeX

example.ps

printer

example.doc

Word

Different strategies for creating formatted text file:

Text Formatters

• Groff was first in 1969

• LaTeX most popular since 1974

• Used extensively in scientific pub’s

• Formatting commands embedded in text.

• Run “latex” to convert .tex to .ps file

• Advantages: free & saves space!

Word Processors

• Popular among general public since 1980s.

• WYSIWYG– Formatting commands are invisible

• Entire document in 1 file

• Many features: spell checking, word count, readability, etc.

• Not free, generally requires more space.

Example

• My vita is a 2-page document

• LaTeX– vita.tex has 4,210 bytes– vita.ps has 43,675 bytes (can delete!)

• Microsoft Word– vita.doc has 31,232 bytes

Spell Checking

• One feature of MS Word is spell checking

• Looks up each word in its “dictionary”

• Uses binary search to make lookup fast!

• Analogy: Try to guess my number 1-100.

Binary Search

• If dictionary has 100 words, need 7 guesses to see if word is spelled right.

log2 100 ~ 7

• What if 1,000 words?

• A real dictionary may have > 25,000 words.

Example

• Looking for “goat”. Here are guesses:

Joachin, degumming, gale, holly, guideline, gloomy, granite, golly, gnu, …

• Notice they go back and forth.

CS 16 – Feb. 25

• Text vs. Hypertext

• Web terminology

• Domains

• HTML

Hypertext

• A text document that contains links to other documents.

• Also may contain “multimedia”

• Filename *.html

• Software: editor…browser.

Some terminology

• Internet = global “network of networks”

• Some Internet applications:– WWW = linked documents on the Internet– E-mail– chat– FTP = file transfer prototcol

Web terminology

• HTML = standard language for hypertext

• Web page = hypertext document (*.html)

• Web site = collection of pages & folders usually starting with index.html

• Web server = machine containing site

• Web browser = program that interprets HTML to show on screen

Web addressing

• Location of file is given by a Web address or URL.

http://www.seds.org/billa/tnp/saturn.html

• saturn.html = page

• billa/tnp = folders

• www.seds.org = site [ server.place.domain]

Domains

• Three letter for U.S. (.com, .org, .net, .edu, .mil, .gov)

• Two letter for countries (.ca, .uk, .za, .ch, .de, .is, cn, .at, .us ………)

• Beware of exceptions

• Newer domains (.info, .museum, .biz, …)

Making Web pages

• Web pages written in HTML. 2 ways…

• Type in HTML code in text editor.– Enter “tags” as you go.

• Use “web generator” such as Dreamweaver– WYSIWYG

HTML format

• Web browsers read HTML files.

<html>

<head> ... </head>

<body> ... </body>

</html>

• Head section is optional• Body contains material to appear in browser

window.

Minimal example

• The simplest Web page contains text.– Can format with various font commands …

<html><body> Hello!</body> </html>

Common tags

• h1, h2, etc. = headings

• br = line break

• p = paragraph

• ol, ul, li = used for lists

• hr = horizontal rule

• b, i = bold or italic

• sub, sup = subscript or superscript

Examples

• 7 <sup> th </sup>

• Who wrote <i> Das Rheingold </i> ?

• <ul>

<li> Gold </li>

<li> Silver </li>

<li> Bronze </li>

</ul>

CS 16 – Feb. 27

Text & Hypertext (continued)

• Readability• Fonts• Surfing the Web

Readability

• First, need to measure:– Words per sentence– Syllables per word

• How to Write Plain English by Flesch:206.835 – 84.6*spw– 1.015*wps

90’s = fifth grade

30’s = college level

Fonts

• Font = style of printing– Typeface– Point size– Ex. Times 10, Helvetica 12

• Fonts can be distinguished by– Sarif or sans sarif– Proportional or non-proportional

Font types

• Sarif = has feet

• Sans sarif = no feet– Look at: i, h, n, r, … (but not t!)

• Proportional = width of characters changes• Non-proportional = all have same width

Web Surfing

• Type in URL (if you know it)

• Start with index site

• Search engine– Quotes “swan lake”– Minus waterloo –university

• Example results

Some sites

• world.altavista.com

• maps.live.com

• factfinder.census.gov

• www.htmlhelp.com

• www.alexa.com

• nces.ed.gov/ipeds

• www.getaway.co.za

Privacy & Cache

• Different browsers & versions behave slightly differently….

• Issues– security on site (https:// or .shtml)– browser cache– cookies

• Browsing anonymously– www.anonymouse.org– ads based on your location

Web issues

• Check date of article

• Check for corroborating info

• Mistakes & bias

• Some things harder to find on the Web?

• Internet quite powerful when you combine 2+ sites or programs– Ex. Searching for airfares, hotel rooms

Scavenger hunt• Looking for a house…

– Real estate Website to find listings– Google earth to look at house & lot– Mapquest to find nearest school, stores

• Media bias– Google news collects headlines– Is the set of “news sources” biased?

• International issues– In some countries, Internet access is restricted!– Languages other than English

CS 16 – March 4

• Results of scavenger hunt – Save until lab

• Computer program – Chapter 8 in book (skip chapter 7)– I/O can take various forms– Programming languages

• Examples: Javascript

I/O• A program’s input may be:

– Numbers

– Text

– File

– Button / click

– Image (rarely)

– Sound (rarely)

• A program’s output may be:– Numbers

– Text

– File

– Image

– Sound (rarely)

A computer program can read and create files, interact with the Web, and create images & other multimedia.

Evolution of programming

• Machine language• Assembly language

– Unique to each manufacturer

• High-level language– FORTRAN, COBOL– Pascal, Algol, Ada– C, C++– Java, Javascript

Example

• How would we calculate:

12 + 22 + 32 + … + 202 ?

• Let’s create our own solution, and see what the “code” looks like in different languages:– Machine language – Assembly language – High-level language

Machine language

00003000: 00000014

00004000: 200c0001

00004004: 20080000

00004008: 3c0a0000

0000400c: 354a3000

00004010: 8d4a0000

00004014: 018a4822

00004018: 1d200005

0000401c: 018c0018

00004020: 00005812

00004024: 010b4020

00004028: 218c0001

0000402c: 08001005

00004030: 2008000a

00004034: 0000000c

help me!

Assembly language

numValue: .word 20

__start:

addi $12, $0, 1

addi $8, $0, 0

lui $10, 0

ori $10, $10, 0x3000

lw $10, 0($10)

while:

sub $9, $12, $10

bgtz $3, end

mult $12, $12

mflo $11

add $8, $8, $11

addi $12, $12, 1

j while

end:

addi $8, $0, 10

syscall

HLL (Pascal)

var

sum : integer;

count : integer;

begin

sum := 0;

for count := 1 to 20 do

sum := sum + count * count;

writeln(sum);

end.

Some languages

• C++ is a general-purpose language.– Especially good for simple tasks.

• Java: lot’s of built-in features – Graphics, automatically surf web

• JavaScript language useful with HTML.– We’ll look at examples.

Javascript

• Can write simple programs little/no overhead or prior experience

• Purpose of JS is to give “life” to Web pages.• Works with a Web browser

– First, create HTML file using a text editor.

– Refresh the browser when you make a change.

• Online guide– http://www.w3schools.com/js/js_examples.asp

Minimal example

• The simplest Web page contains text.– Can format with various font commands …

• To insert Javascript code, put inside the body:<script type=“text/javascript”> ... </script>

<html><body> Hello!</body> </html>

Simple JS features

• Printing a message– <br> means break to the next line

– <h1> is a heading level – prints big & bold

• Using variables• Looking up time• Making choices• Loop

CS 16 – March 6

• Software problem solving – Process– Uh-oh’s– General examples

• Javascript– Fixing the time program– Revisit earlier examples

Process

• The “usual” procedure for writing a program from scratch involves these steps:– Read & understand the problem

– Explain how to solve the problem in English.

– Write solution in the desired programming language

– Compile the program• Some languages like Javascript don’t need to be compiled:

their instructions are interpreted, e.g. by a browser.

– Run the program, check the output.

CS 16 – March 16

• Javascript– Responding to a prompt (handout)– Forms (handout)

• Possible mistakes (“bugs”)– Fixing the time program

Javascript forms

• Interactive I/O• User types inside a text box or text area, and clicks

a button to “submit” answer.• A function “validates” or does some computation.

Can announce answer in an “alert” box.

• Examples (handout)

CS 16 – March 18

• Finish Javascript examples– Guessing game (prompt)– Online quiz, counting words (forms)

• Possible mistakes (“bugs”)– Fixing the time program

Bugs

• Any mistake in a computer program

• Coined by Grace Hopper, ca. 1950.

• Three kinds of bugs:– Syntax errors– Run-time errors– Logical errors

• Beyond bugs, program can be just slow!– Ex. Finding the divisors of some number.

CS 16 – March 19

• After running a program…– Fixing bugs– Making enhancements

• Sorting

Javascript practice

• Time program (js1)– Need to print extra 0 in case of “10:05”. We

don’t want 10:5– How would we convert to a different time

zone?– Am/pm ?

• Image array (js images)

Sorting

• Much-studied problem in CS – many ways to do it• You have a list/array of data, and need to arrange

it “in order” • Possible strategies:

– Find the largest value and put it first, find 2nd largest value and put it 2nd, etc.

– Scan the list and see which ones are out of order and swap them

– See http://cg.scs.carleton.ca/~morin/misc/sortalg

CS 16 – March 23

• Review sorting– insertion, selection, bubble, merge

• Operating Systems (Chapter 10)– Ultimate program

– Intimate with the hardware

– Responsibilities…

– Examples

Operating Systems

• Computer is like a 3-story building• OS manages the whole machine;

interfaces with us.

Applications

Operating System

Bare hardware

OS Manages…

• logins, logouts, passwords• multitasking• memory• files• I/O• user interface• security

Passwords

• Login: username & password

• Password security– Many combinations– Penalties for mistake– Password file is encrypted

Resources

• Need to manage printer, files, etc.

• Synchronization– Ex. 2 machines want to print at same time– Ex. Copy a file that’s currently in use

– Detect if available– Need to temporarily “lock” the resource

Multi-tasking

• Defn – doing multiple things at once

• Practical defn – make it appear as though…

• Time quantum (0.1 sec)

• Processes take turns using the CPU

Memory mgmt.

• RAM is much faster than disk, but smaller• OS determines what belongs in RAM

• When RAM gets crowded, less-used files sent back to disk.– Like a small kitchen counter that can’t hold all your

recipe’s ingredients.

• Thrashing

CS 16 – March 25

• Operating Systems (continued)– Memory management

– Process states

– Scheduling processes on the CPU

Memory mgmt.

• RAM is much faster than disk, but smaller• OS determines what belongs in RAM

• When RAM gets crowded, less-used files sent back to disk.– Like a small kitchen counter that can’t hold all your

recipe’s ingredients.

• Thrashing

Processes

• A process is an executing program.• OS must keep track of all the work it’s doing, in

case of interruption (e.g. hibernate mode).• Possible states for process (p. 338)

– Ready (could execute, but doesn’t have CPU)

– Running (in CPU)

– Waiting (doing I/O operation)

Process scheduling

• Extensively studied in CS !• Look carefully at examples pp. 340-342.

• 3 common techniques– Round robin (we saw this one already)

– First-come, first-served

– Shortest Job Next

Scheduling

• Round-robin– Fair: give each process an equal time quantum.

– Usually not long enough to finish, so pre-empt. Pre-emption incurs some overhead, so there are alternative strategies:

• First-come first served– Do the tasks in the order in which they are requested

• Shortest job next– Try to minimize the average completion time. Do the

easy/short tasks first.

Measuring a schedule

• To tell how good a schedule is, we can compute the average turnaround time.– People are usually interested in how long it takes for

their jobs to get done.

– Turnaround time = (time @ finish – time @ request)

Example

Process number Time of request (ms) Execution time needed

1 0 20

2 5 30

3 10 40

4 20 10

First-come, first-served:Process 1 can execute from t=0 to t=20Process 2, t=20 to t=50Process 3, t=50 to t=90Process 4, t=90 to t=100

What is the average turnaround time?

CS 16 – Lab #10

Databases (Microsoft Access)

• 4 parts of a database

• database design– Try to understand the ideas behind database

design, not just the mechanics.

Access vs. Excel

• Excel emphasizes numbers

• Access emphasizes relationships

• some overlap

• Access is perfect for finding common info from 2 separate tables

Purpose of Access

• It’s a “database management system”

• Record keeping for a business– Requires a plan– one file, with many components

• Keep track of … so that:– Find cross-references– Generate reports

Database format

Usually four parts:

• Tables (at least 1 is required)

• Queries

• Forms

• Reports

Navigating a table

• A database table looks like a spreadsheet!

• Record = row

• Field = column

• Two ways to view:– Design view, to start– Datasheet view, to enter data

• Primary Key!

Example questions

• In a stock portfolio:– Which stocks have lost money?– When did I buy those stocks?

• Which class is easier: CS 22 or CS 25?– Check grades in each class– Check grades for students who’ve taken both

• Among customers who bought a new generator last year, what have they bought since?

Relieve tedium

• Suppose we want to maintain info on orders.

• Better to have two tables than one!

Order# Name City State Product Qty.

101 J. Miller Miami FL Laptop 5

102 G. Novak Tampa FL Printer 3

103 G. Novak Tampa FL DVD-RW 50

104 G. Novak Tampa FL Keyboard 1

105 J. Miller Miami FL Lamp 4

106 A. Bik San Diego CA Chair 6

107 T. Lee Buffalo NY Fan 3

Need multiple tables

• Ex. Librarian wants to contact graduating seniors who have overdue books.

• Need multiple tables:– Student info table

• Student #, name, year

– Book table• ISBN, title, author, …

– Transaction or “check out” table• Transaction #, ISBN, student #, Due date

Relationships

• When you have 2+ tables, there is almost always a relationship

• They share one field in common.– Can you tell what it is?

• Ex. Customers & Orders• Ex. Students & Class roster• Ex. Publishers & books

Animal hospital

• Keep track of customers, pets, visits

• Each gets its own table– What fields for each table?– Relationships

• What else does a database need?

Relationships

Fields in your table

• Anticipate questions– Age? store birth date– GPA? store credits and quality points– What year? store date of admission

• Store data in its smallest parts (e.g. address)

• Calculated fields don’t belong in table!

CS 16 – March 27

• Review of scheduling– 3 algorithms

– Turnaround time

– Possibility of idle time

• General review

Examples

Process number Time of request (ms) Execution time needed

1 0 20

2 5 30

3 10 40

4 20 10

Process number Time of request (ms) Execution time needed

1 0 10

2 30 30

3 40 20

4 50 5

Outline for test

• Excel– text functions, scenarios, solver, goal seek (Chapter 8)

• Dreamweaver (3 labs)• Javascript• Text software• Web terminology & concepts• HTML• Database – intro terminology

• Problem solving/software– Steps in solving problems

– Types of languages & statements

– Variables

– Example algorithms: search, sum, sort

– Kinds of bugs & how to fix them

• Operating systems (just chapter 10)– Various responsibilities

– scheduling

CS 16 – March 30

Operating systems (continued)• Examples• System “load”

• File system: Chapter 11– Managing files, accounting, quotas

– Permissions

– How to search for a file.

Popular OS’s

• 1971 UNIX, Linux• 1979 DOS

• 1983 Microsoft Windows• 1984 MacOS

• 1980 QNX (a real-time OS)

User interface

• Text-based– Enter commands at the keyboard

– Program called a “shell” awaits your commands.

• GUI– Popular since mid 1980s

– Uses mouse

– Can see multiple applications on screen

– Examples: http://toastytech.com/guis

Cutting Edge

• Real-time OS– Assumes all jobs have deadlines

• Distributed OS– Your running program and/or files may be on a

different machine

• High Performance Computing– Using multiple CPUs at once– Technique is called “parallel processing”

System load

• A measure to show how “busy” the CPU is• At an instant: how many tasks are currently

running or ready– If load > 1, we have “overloaded” system, and work is

starting to back up. Should stop requesting more jobs.

• Typically reported as an average over the last 1, 5 or 15 minutes.

File mgmt.

• For each file/folder, OS knows:– Name– Size– Type ( icon and what program to open)– Owner– Group– Permissions

• In multi-user system, users may have quota.

CS 16 – April 1

• File system: Chapter 11– Managing files, accounting, quotas √– Permissions– How to search for a file.

• Handout: 2nd Access lab.

File permissions

• 3 levels: owner, group, rest of world

• For each level– ‘r’ = can I read the file?– ‘w’ = can I write to (or delete) the file?– ‘x’ = can I execute the file?

• Ex. rw-rw-r-- (664)• Ex. rwxr-xr-- (754)

Common permissions

• Most of the time, we don’t use “groups,” so the group permission = everybody else

644

600

755

700• Only owner* can change permissions

File Organization

• Hierarchical– Files in folders, folders inside bigger folders

– E.g. C:\work\sp09\cs101\excel\calorie.xlsx

– Can visualize entire file system as a tree.

• How to search for a file?– First, need some “key” info to search on.

– Then, traverse the tree in organized fashion until you find file.

Traversing a tree

2 basic strategies• Breadth-first search (BFS)

– Start at the root (top) of tree

– Fan out in all directions simultaneously– Good if you think what you’re looking for is near the top.

• Depth-first search (DFS)– Start at the root, as usual

– Go as far as you can down one path of the tree.

– If not found, back up and try another path.– Good if you have an idea what area to search first.

ExampleSuppose we’re looking for file at node 9.

We visit the nodes of the tree in the following order.

BFS: 1, 2, 3, 4, 5, 6, 7, 8, 9

DFS: 1, 2, 4 – back up

5 – back up

3, 6, 7, 9

1

2 3

4 56

7 8

9 10 11

CS 16 – April 6

Databases

• How tables work

• Relationships– Queries without relationships– 3 kinds of relationships– Practice

Table review

• We want to “manage” information:– Organize, insert, delete, retrieve

• To organize we…– Create a table (or “set”, “class”)

consisting of records (or “objects”)each having fields (or “attributes”)

• Usually we’ll want 2+ related tables.

Fields in your table

• Anticipate questions– Age? store birth date– GPA? store credits and quality points– What year? store date of admission

• Store data in its smallest parts (e.g. address)

• Calculated fields don’t belong in table!

Queries

• Usually we ask about info from 2+ tables.• By default, a query will perform an operation

called a Cartesian Product, which gives all possible combinations.

• Ex. Name and City tables:

Name

Bob

Mary

Ken

City

Miami

Pittsburgh

Cartesian Product

• Given 2 sets, find all possible ordered pairs.– Analogously for more than 2 sets.

• Great example: choosing a menu.– Appetizer– Entrée– Dessert

• Unfortunately, most DB queries are not like this! We get too many results.

Relationships

• We want to tell Access that there is a relationship between the tables, so we can create meaningful query.

• One-to-many is most common– “Each city has one or more employees.”– Now, query will return 3 results instead of 6:

Miami BobPittsburgh Mary

Ken

One-to-One

• Can be useful if some information is confidential.

• What if we didn’t have any relationship?

Empl # Name Position

101 Smith Welder

102 Jones carpenter

Empl # Salary

102 18,000

101 17,000

1-1 Query

• When you combine tables that have a 1-1 relationship: Access will look for fields that are the same, and use this as a filter.– In previous example, we’ll have 2 results

instead of 4. Employee 101’s informationEmployee 102’s information

– Let’s look at another example.

• What happens when we “join” these 1-1 tables?

First name Last name Position City

Bob Fuller accountant Chicago

Bob Daniels cashier Greenville

Bob Daniels accountant Indianapolis

Alice Andrews gardener Greenville

First name Last name Salary Birthday

Bob Daniels 51,000 7/1/67

Elena Carlson 21,000 9/1/89

Alice Andrews 81,000 8/1/78

First Last Position City Salary Birthday

Bob Daniels cashier Greenville 51,000 7/1/67

Bob Daniels accountant Indianapolis 51,000 7/1/67

Alice Andrews gardener Greenville 81,000 8/1/78

First name Last name Position City

Bob Fuller accountant Chicago

Bob Daniels cashier Greenville

Bob Daniels accountant Indianapolis

Alice Andrews gardener Greenville

First name Last name Salary Birthday

Bob Daniels 51,000 7/1/67

Elena Carlson 21,000 9/1/89

Alice Andrews 81,000 8/1/78

CS 16 – April 8

• Database Relationships– 3 kinds of relationships

– Practice with several tables

• Just 2 more big topics:– Image enhancement

– communication

One-many Relationships• Referential integrity

– Keep related records consistent

– Cascade delete: allow deletion of “one”

– Cascade update: allow update of “one”• For example, changing someone’s CustomerID.

Many-to-many

• Ex. Customers to products

• Implement as 2 one-to-one

• “Order details” table

• Think of possible queries based on the 5 tables given in handout.

Other queries

Besides ordinary “select” queries:

• Total – special case: also do subtotals • Parameter – prompt user to tailor the result

• Action – modify underlying table– Make, delete from, append to, update

• Crosstab – 2-D subtotal– Ex. $, by species and month!

Enhancing an image

• Input = original image (x)

• Output = final image (y)

f

Brighten

• To brighten, we increase pixel values.

• Simple function like y = x + 20 won’t work

• Real filter functions have complex formulas– Better to “draw” the filter function

Filter function

• Axes for input and output pixel values

0 2550

255

0 2550

255

Brighten

• We want output > input.

0 2550

255

0 2550

255

brighter

darker

Darken

• We want output < input.

0 2550

255

0 2550

255

brighter

darker

Increase contrast

• What do we want?

0 2550

255

0 2550

255

brighter

darker

Increase contrast

• Bright get brighter; dark get darker

0 2550

255

0 2550

255

brighter

darker

128

Decrease contrast?

• What should this look like?

0 2550

255

0 2550

255

brighter

darker

128

Decrease contrast

• “Robin Hood”

0 2550

255

0 2550

255

brighter

darker

128

CS 16 – April 15

Communication (Ch. 15)

• Basic communication model

• Cryptography

• Error detection

• Local Area Networks

The model

• Claude Shannon, 1940s

• Broadcast = 1 to many

• Networking = 1 to 1

Six elements:• Source• Destination• Transmitter• Receiver• Channel/medium• _____________

For more on Shannon’s vast contributions, please watch http://www.uctv.tv/search-details.asp?showID=6090

Two directions

• Transmit: – Encode your message in binary (e.g. ASCII)– Encrypt if desired

• Receive:– Decrypt if necessary– Decode from binary to ordinary text

Cryptography

• Big research area

• Terminology:– Plaintext– Ciphertext– Encrypt & decrypt functions

Encryption examples

• Caesar cipher

• Cryptogram

• One-time Pad & Japanese Naval Codes– Dictionary table– Additive table– Destroy each page as you use it

Breaking codes

• Like solving a cryptogram

• Distribution of letters (‘e’ versus ‘q’)

• Digraphs, trigraphs

• Common words

• Eric Nave’s “Betrayal at Pearl Harbor”

Errors in transmission

• Random flipping of bits

• Prepare by using parity bit– Add 9th bit to each byte– Goal is that each byte has even # of 1’s– Receiver checks each byte

– Doesn’t solve every error!

CS 16 – April 17

Communication, continued

• Error detection

• Local Area Networks

• Next week: how the Internet works

Errors in transmission

• Random flipping of bits

• Prepare by using parity bit– Add 9th bit to each byte– Goal is that each byte has even # of 1’s– Receiver checks each byte

– Doesn’t solve every error!

Local Area Networks

• Sharing resources in a lab– File server– Printer

• Communication based on topology– point-to-point – star – bus (like speaking at dinner table)– ring (need token to send message)

Bus topology

• All machines share the same channel

• All continuously listening

• “Ethernet” protocol (dinner table)– don’t talk when someone else is talking– collisions

• Amplify signal with repeaters

Token ring

• Fast messaging over larger distances

• Logically arranged in loop

• Messaging: Token passed around the ring.– Am I busy?– From– To– message

Token action

• When you receive token:

• Is the message for me?– If so, read and change to ack.– If not, just pass token.

• Do I need token?– Wait until it comes back as not “busy”

Example

• 4 machines: A, B, C, D.

• A has message for C.– When A gets token, writes message for C.– B passes token.– C receives msg, sends ack message to A.– D passes token.– A receives ack, clears token. …

Example #2

• We have 4 machines A, B, C, D.• What happens when…

– Token starts at D.– A has a message for C.– C has a message for A.– B has a message for D.

…………………………………………

CS 16 – April 20

Communication, continued

• Token ring communication

• Internet applications

• How the Internet works: TCP/IP

Example

• 4 machines: A, B, C, D.

• A has message for C.– When A gets token, writes message for C.– B passes token.– C receives msg, sends ack message to A.– D passes token.– A receives ack, clears token. …

Example #2

• We have 4 machines A, B, C, D.• What happens when…

– Token starts at D.– A has a message for C.– C has a message for A.– B has a message for D.

…………………………………………

Internet applications

• FTP (file transfer)

• E-mail

• Chat / talk

• Gopher

• WWW

• High-performance computing

Each application: “port” on machine

TCP

Transfer Control Protocol

• Break up message into packets

• Sequence number on each packet

• Receiver detects lost packets

• How big should a packet be?

IP

Internet Protocol • Every machine has IP address

– 156.143.128.20

• Packets are individually addressed• Routers• Not all packets go the same way!

– Just like 2 people driving to Seattle might not take the exact path.

CS 16 – April 22

Communication, continued

• Routers

• Dijkstra’s shortest path algorithm

Behind the scenes

• “ping” program– Send empty packets, check for ack– 75 ms to San Diego… 840 ms to Pretoria

• “traceroute” program– Lists all routers between here and another

machine

Dijkstra’s algorithm

• How do you find the shortest path in a network?• General case solved by Edsger Dijkstra, 1959

4 7

3

6 8

3

1 6

9

2

7 4

• Let’s say we want to go from “A” to “Z”.

• The idea is to label each vertex with a number – its best known distance from A. As we work, we may find a cheaper distance, until we “mark” or finalize the vertex.

1. Label A with 0, and mark A.

2. Label A’s neighbors with their distances from A.

3. Find the lowest unmarked vertex and mark it. Let’s call this vertex “B”.

4. Recalculate distances for B’s neighbors via B. Some of these neighbors may now have a shorter known distance.

5. Repeat steps 3 and 4 until you mark Z.

4 7

3 4

2

A

B C

Z

First, we label A with 0. Mark A as final.

The neighbors of A are B and C. Label B = 4 and C = 7.

Now, the unmarked vertices are B=4 and C=7. The lowest of these is B.

Mark B, and recalculate B’s neighbors via B. The neighbors of B are C and Z.

– If we go to C via B, the total distance is 4+2 = 6. This is better than the old distance of 7. So re-label C = 6.

– If we go to Z via B, the total distance is 4 + 3 = 7.

4 7

3 4

2

A

B C

Z

Now, the unmarked vertices are C=6 and Z=7. The lowest of these is C.

Mark C, and recalculate C’s neighbors via B. The only unmarked neighbor of C is Z.

– If we go to Z via C, the total distance is 6+4 = 10. This is worse than the current distance to Z, so Z’s label is unchanged.

The only unmarked vertex now is Z, so we mark it and we are done. Its label is the shortest distance from A.

4 7

3 4

2

A

B C

Z

Postscript. I want to clarify something…

The idea is to label each vertex with a number – its best known distance from A. As we work, we may find a cheaper distance, until we “mark” or finalize the vertex.

When you are mark a vertex and look to recalculate distances to its neighbors:

– We don’t need to recalculate distance for a vertex is marked. So, only consider unmarked neighbors.

– We only update a vertex’s distance if it is an improvement: if it’s shorter than what we previously had.

4 7

3 4

2

A

B C

Z

CS 16 – April 24

• Final thoughts on Communication– Transmitting messages √

– LANs √

– TCP/IP √

– Shortest path √

– Download speed

• Review

Snooping

The “dark side” of TCP/IP

• Web site can track you by IP address– Localized marketing– Privacy concerns

• Anonymous IP servers– Ex. “Anonymouse”

Shortest Paths

• Dijkstra’s algorithm:

What is the shortest distance between 2 points in a network/graph ?

• A related problem:

What is the shortest distance for me to visit all the points in the graph and return home?

This is called the traveling salesman problem. Open question in CS: why is this problem so hard?

B

A C

DE

8 6

6

4

3

2

4

9

5

12

Measuring speed

• Overhead = prepare & assemble message

• Flight time = first bit to arrive at destination

• Bandwidth = max rate to propagate data

(cruising speed)

• Total time =

overhead + flight time + (msg size)/bandwidth

How much longer?

File Size Progress “time left” rate

#1 815 KB 65.1% 3:08 1.5 KB/s

#2 5.9 MB 64.8% 24:03 1.5 KB/s

Examples

Course outline

• Binary representations– Numbers– Text– Images– Linear vs. nonlinear information

• Excel– Formulas, functions– Tools: Solver, Goal seek, sorting, pivot tables …

• Computer organization– Logic gates & Finite automata– Instruction execution & pipelining

continued

• Memory system• Access

– Queries, relationships, etc.

• Problem solving– Recipes

– Program structure

– Javascript

• Hypertext, Web, Dreamweaver

continued

• Operating systems– Responsibilities

– Process scheduling

• Image processing– Filter functions

– Photoshop

• Communication