Key ideas from last time
- what computer science is not
- instead, c.s. is the study of algorithms
- algorithm: well-ordered sequence of unambiguous,
effectively computable operations... (that halts!)
- algorithm can be formalized, transmitted to computing agent that
does not understand problem
- abstraction: black-box analogy
Pseudocode for expressing algorithms
- why not natural language?
- too verbose
- does not visually indicate structure
- context-dependent
- inherently ambiguous
- why not concrete programming language?
- too much emphasis on syntax
- for human reader, requires familiarity with quirks of p.l.
Pseudocode is a compromise
- natural language ⇒ pseudocode ("algorithm discovery")
- pseudocode ⇒ programming language
- import of readability / ease of visualization
- pseudocode not formal: be consistent, but tune
depending on
kind of problem and intended audience
- why is it unrealistic to program in pseudocode?
Sequential operations
- computation: "assignment" of arithmetic expression to variable
- mailbox analogy for variables
- assume standard arithmetic ops are "primitive"
- examples:
f ← 9c/5 + 32
i ← i + 1
- input/output: need not be numeric nor of same kind
- abstraction again: we ignore details of input/output
Example: Compute average of 3 values
(Practice problem #1, p. 45)
get input values x, y, z
sum ← x + y + z
avg ← sum / 3
print avg
Conditional operations
- decisions rather than straight-line calculations
- compound: refers to other, simpler ops
- if-then-else (sometimes we ignore else)
get input value n
if n divided by 2 has no remainder then
print "even!"
else
print "odd!"
"else" may be on its own line for visual formatting
Iterative operations
- repetition - where computation gets interesting
- without loops - algorithms must halt!
- with loops - even small ones might not
- loop also compound; in fact it contains conditional
or else it
must be infinite
get input value n
p ← 1
i ← 1
while i ≤ n:
p ← p * i
i ← i + 1
output value p
Bottom-up reductionism
- believe it or not: that's all there is!
- from basic arithmetic, conditional, and iterative ops:
any
algorithm can be constructed
- challenge yourself to find counterexample