CS 16 Jan. 13

- 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 (dont 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 computers 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

Course topics

- Representing information in binary form.
- What a computer system is made of.
- A problem solving machine!
- Spreadsheets, databases, image processing,
- Giving commands to the computer
- Exercise Please read chapter 1

CS 16 Jan. 15

- A little history
- Binary number
- Conversions
- Shorthand

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
- Moores Law

(No Transcript)

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 lets try base 2 What is 11010?
- 1 24
- 1 23
- 0 22
- 1 21
- 0 20
- More concise to simply say
- 24 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

- Lets say we have 4 bits.
- What is the lowest number?
- What is the highest number?
- Try same experiment with 5 bits.

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

- Lets 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 lets go the other way
- 1110002 ______16
- 100111112 _______16

CS 16 Jan. 20

- Recap octal hex shorthand
- Chapter 3 data representation
- Many kinds of data ? all in binary
- Today integers
- Unsigned
- Signed
- Later text, images, code, etc.

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 couldnt the computer scientist tell the

difference between Halloween (Oct 31) and

Christmas (Dec 25) ?

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. Its either 1030

or 1031

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 repn

- Most often 8, 16, or 32 bits
- For our examples, well 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 repns to be negative.
- Ex. 5 bits ? 32 numbers.
- 16 numbers are negative
- Thus, range is 16 to 15.
- For n bits range is 2n1 to 2n 1 1

How to represent negatives

- In unsigned, impossible!
- In signed 3 steps to represent x
- Find repn of x.
- Invert the bits.
- Add 1.
- Try some examples.

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 repn as unsigned.
- Technique for x doesnt work for 16.

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 dont 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(b1b4)
- Excel functions are very convenient! Well use

about 10-20 of them.

Hints for formulas

- Use cell ranges, like B3C7
- Absolute reference
- Wont change when formula copied/moved
- Signify with , as in E9
- 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. 22

- Number representation
- Integer
- Unsigned v
- Signed v
- Sign-magnitude v
- 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 repn scheme. Lets 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

- Lets 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

- Lets 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

- Lets 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 weve seen .4 already.

____ - Answer is .1 0110 0110 0110 or .10110

Real-number repn

- 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

CS 16 Jan. 27

- 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
- Compression

Distribution

- 8 bit exponent ? 256 different exponents
- Biggest number 1038.
- Smallest () number 1038.
- 23 bit mantissa ? 8 million numbers per power of

2. - Three kinds of numbers cant 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 - Its 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 theres 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. Theres a hierarchy because of the

order of operations.

3

4

7

8

Representing a tree

- Normally wed write
- (3 4) (7 8)
- More efficient to use postfix or RPN notation
- 3 4 7 8

3

4

7

8

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 d ? - 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.

CS 16 Lab 3

- Excel
- Review values, formulas, functions
- Absolute and mixed references
- Creating Charts ?

Functions in Excel

- sum(a1a4) better than a1a2a3a4
- Function menu
- Can fill in the blanks step by step
- Example loan payment
- Use pmt function
- Takes 3 parameters, but too much to remember

(No Transcript)

Absolute references

- Purpose
- For constants in a formula
- When you dont want a cell reference to change

when the formula gets copied - Use as in E3 (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.
- B7 When we copy, only col changes.
- Lets 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 lt 65, Heat, A/C)
- Ex. if(D8 gt 0, D7 / D8, )
- Lets look at climate-data example

vlookup function

- Shortcut for doing lots of ifs in a row.
- Ex. Grading scale
- if (B7 gt 90, A, if (B7 gt 80, B, if (B7 gt

70, C, if (B7 gt 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)
- Insert?Chart

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. 29

- Huffman code compression
- Image representation
- B/W and color schemes
- File size issues

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. - Were given set of letters used in message, and

their frequencies. - Ex. A5, B10, C20, D25, E30
- Ex. P5, N10, D10, L15, A20, S20, E30
- Arrange frequencies in order
- Group the letters in pairs, always looking for

the smallest sum of frequences ? Create a tree!

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 shouldnt change

Properties of repn

- 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

Picture resolution determines both the amount of

detail as well as its storage requirements

- here is a (edited) digitized image with a

resolution of 272 x 416

Resolution

Picture resolution determines both the amount of

detail as well as its storage requirements

- notice the changes when the resolution is reduced

(136 x 208)

Resolution

Picture resolution determines both the amount of

detail as well as its storage requirements

- notice more changes when the resolution is

reduced (68 x 104)

Dynamic Range

DYNAMIC RANGE refers the number of values for the

measuring scale used in quantizing

- Here is an intensity or graylevel image with 256

levels (i.e., 0 to 255 scale)

Dynamic Range

DYNAMIC RANGE refers the number of values for the

measuring scale used in quantizing

- Here is an intensity or graylevel image with 16

levels (i.e., 0 to 15 scale)

Dynamic Range

DYNAMIC RANGE refers the number of values for the

measuring scale used in quantizing

- Here is an intensity or graylevel image with 4

levels (i.e., 0 to 3 scale)

Dynamic Range

DYNAMIC RANGE refers the number of values for the

measuring scale used in quantizing

- Here is an intensity or graylevel image with 2

levels (i.e., 0 to 1 scale or a binary image) - Dithering can help

Dont 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 repns

- 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.
- Examples
- black (0, 0, 0)
- purple (75, 0, 100)
- white (255, 255, 255)
- How about (x, x, x) or (0, 0, x) ?

RGB examples

Color 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 examples

Color 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

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

brightness

Trade-off between saturation and brightness

hue

saturation

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

CS 16 Feb. 3

- Chapter 4 How computers think
- Logic gates (basic building blocks)
- Turing machine model
- Finite state machine model
- a.k.a. Finite automaton

Logic Gates

- Basic building blocks
- Usually 2 inputs
- X, Y could be 0 or 1.
- 1 true
- 0 false
- By combining 2 gates, you get more sophisticated

functions

AND and OR

AND AND AND

X Y ans

1 1 1

1 0 0

0 1 0

0 0 0

OR OR 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 XOR 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.

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 its 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.

S

x

y

C

z

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)
- Insert?Chart

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
- Home?Editing?FindSelect?Go To

CS 16 Feb. 5

- How computers think (continued)
- Finite state machine model
- a.k.a. Finite automaton
- Representing accepted input as a regular

expression

Finite Automata singular 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

5

5

10

10

5

25

15

20

25

5

5

Binary example

- We want a word starting with 101

need 101

need 01

need 1

?

1

0

1

1

0

0

0,1

?

Binary Example (2)

- We want a word with at least two 0s.

0

need two

need one

?

0

0,1

1

1

- What if we wanted exactly two 0s?

What does this FA do?

1

A

B

0

1

0

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 - Examples
- 101 anything starting with 101
- Jan??.ppt file names like jan26.ppt or

jan14.ppt - furman.xlsx any spreadsheet about Furman

CS 16 Feb. 10

- Chapter 5
- CPU and memory
- Carry out instructions from software.
- John von Neumanns 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) Time (clock period) Speed (clock rate) 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

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?

Improving performance

- To reduce time, we can
- Run fewer instructions
- Take less time for each instruction
- Faster clock ? Well look at this ?
- Marketing can cheat!

Cycle F D X

1 1

2 1

3 1

4 2

5 2

6 2

7 3

8 3

9 3

- How many cycles to execute 7 instructions?

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 instruction
- 1 cycle for each of the rest
- 4 (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?

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 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
- Home?Editing?FindSelect?Go To

Pivot Tables

- Perhaps most important feature of Excel!
- Its 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
- Insert?Pivot 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 (cant undo).

Excels 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. 12

- Finish chapter 5 Memory
- Main memory
- Secondary memory
- Test review today 430 in 204 Riley Hall

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

Disk examples

- Hard drive
- Cant take out. Dont 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 300 020

CD-RW 200 020

Flash 014 002

RAM 001 001

LAN server 004 004

External drive 003 002

CS 16 Feb. 17

- 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, wed 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 its

solving a specific problem Im hungry. ? - What do we see in recipes? Heres 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 its not obvious, sometimes we check

things - Are potatoes fully mashed?
- Should I add more _____ to the mixture?

Recipes (3)

- But we dont 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 Shepherds 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

- Understand problem inputs and outputs
- Write solution in English pseudocode
- Write code in a programming language
- Compile
- 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 cant 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!

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

Summary

- 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.

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 (cant undo).

Excels 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. 19

- 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
- Input ? calculations ? output
- 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.

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.

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

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. v
- Get hours and rate from the user.
- Set the wage as follows
- If (hours gt 40), use overtime formula
- Otherwise, use regular formula
- Output wage

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 temp
- temp counter counter
- Sum sum temp
- Output the sum

CS 16 Feb. 24

- The Joy of Text
- Software for text
- Text formatters vs. word processors
- Spell checking
- Readability
- Hypertext ?

Text Software

- Text editor (Notepad, Wordpad, emacs, vi)
- (Web) Browser (Netscape, Opera)
- Text formatter (LaTeX, Groff)
- Word processor (MS Word)

Different strategies for creating formatted text

file

example.html

example.tex

example.doc

LaTeX

browser

Word

example.ps

See on screen

printer

Text Formatters

- Groff was first in 1969
- LaTeX most popular since 1974
- Used extensively in scientific pubs
- 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