From charlesreid1

Revision as of 19:20, 14 September 2016 by Admin (talk | contribs) (→‎Homework Code)

Chapter 4: Conditional Execution

Sections:

4.1 If/else statements

4.2 Cumulative algorithms

4.3 Text processing

4.4 Methods with conditional execution

4.5 Case study: BMI

Last chapter: solving complex programming problems with repeated tasks using for loops, flexibility via class constants, and user input.

This chapter: conditional execution. Expand our understanding of common programming situations. With new topics, revisit old material.

Section 4.1: If Else

Material

Topics:

  • Logic statements for if/else
  • Operators and operator precedence
  • Equality stuff - objects and == and equals()
  • Refactoring methods with logic
  • and/or operators


Conditional logic

  • Sometimes, but not always, we want to execute particular lines of code.
  • Can use if/else structure to branch execution
  • Relational operators: different kind of operations
    • Up until now, have been doing operations on numbers to obtain new numbers
    • Example, 12*2, assign to new variable int a = 12*2
    • No true/false nature, it is always true because we're creating a definition, we're defining a new rule
  • Now, we'll be using equals in a different sense

"Does a equal 24?" vs. "a is equal to 24"

if( a == 24 ) vs. int a = 24;

Can introduce other comparison operators:

  • Equals
  • Not equals
  • Less than/greater than
  • Less than or equal to/greater than or equal to

Revisit operator precedence:

  • Unary operators
  • Multiplication operators
  • Additive operators
  • Relational operators
  • Equality operators
  • Assignment operators

Nested if/else:

  • Patterns for designing logic structures
  • If red/if blue/if green: can combine into structure, because only one can be true
  • if/else

Nested, only one is true:

if( condition1 ) {
    ...
} else if( condition2 ) {
    ...
} else if( condition3 ) { 
    ...
}

Multiple conditions can be true:

if( condition1 ) {
    ...
}
if( condition2 ) {
    ...
}
if( condition3 ) {
    ...
}

Corresponding diagram representations: (see book)

Finding the pattern:

  • Analyzing the problem helps determine what kind of control structure you need
  • Combination of branches doesn't matter: if statements
  • Only one, or none, of branches should be taken: if/else if/else if
  • Only one, and exactly one, branch should be taken: if/else if/else if/else

Weird equality stuff:

  • For strings and other objects, == doesn't work great
  • This is shorthand for a GENERAL concept, which is, EQUALS

Metaphor:

  • Two numbers: 5 and 5. I know how to check if they're equal. Equality is defined rigorously, based on the way the real numbers are defined.
  • Two lamps: A and B. Are these two lamps equal?
    • Equal in light? Equal in how much power they draw?
    • Equal in appearance? Independent of function? (Wax lamp)
    • Equal in the cosmic sense? Composed of the exact same atoms? What about a perfect atom-by-atom reproduction?
  • Equality is something we have to define

Objects and equality:

  • Always use obj1.equals(obj2), not == (equals() is the more general)

Refactoring/modularizing if/else code:

  • if A: do a bunch of stuff; if B: do a bunch of stuff; if C: do a bunch of stuff
  • rewrite, define an action X, so then it becomes def X do a bunch of stuff; if A do X; if B do X; if C do X

Multiple conditions for if/else:

  • AND operator (if a number is between A and B, that can be expressed as the combination of 2 conditions: number > A, number < B)
  • OR operator (A, or B, or both)

Life Skills

Java debugger - makes understanding conditional logic a whole lot easier, if you can step through a nested set of conditionals.

Section 4.2: Cumulative Algorithms

Definitions

Definitions:

  • Cumulative algorithm
  • Roundoff error

Material

Connect loops with algorithms:

  • Finding average, finding sum, finding min/max

Min and max:

  • Exploring a "simple" idea like taking the maximum can be tricky to implement
  • Let's say we're looking at surface temperature of a planet
  • All negative numbers; if you initialize your minimum to 0, you'll get a minimum of 0 - incorrect
  • To set a maximum: should start with data

Example: hailstone sequence

  • pick a starting number
  • If odd, e.g., do 3x+1, and if even, e.g., do (x/2)
  • Start with an initial minimum/maximum guess
  • Go through sequence, N steps, calculate a minimum and maximum

Example: cumulative sum with if

  • if statement to check for valid input values
  • if statement to count number of negative numbers
  • user input (N steps), user input (numbers)

Roundoff error:

  • Checking equality is tricky due to roundoff error
  • Comes up around cumulative algorithms
  • Example: 2.77500000000000005
  • Float roundoff errors
  • Truncate a number at a certain decimal place
  • Replicating digits lopped off
  • Why, if 2.1 and 3.8, no repeating decimals, would Java turn them into repeating decimals?
  • Due to internal Java representation: representing decimal numbers as powers of 2, not powers of 10
  • Simple example: add 0.1 (can't be represented exactly because base 2)

Checking equality:

  • Use tolerance
abs(A-B) < 0.01

Section 4.3: Text Processing

Definitions

Definitions:

  • Text processing
  • ASCII

Material

Char type:

  • comes from C language
  • strings composed of chars
  • charAt() method

Chars and ints: primitive types

  • have already seen (with Caesar cipher) that we can treat chars like numbers, operate on them, increment them

Cumulative text algorithm

  • Count # characters occurring in string
  • Cumulative concatenation

Printf:

  • More control over print format
  • %d digit, f for float, etc.
  • Table of common print formats
%d
%8d
%-6d

%f
%.2f
%16.2f

%s
%8s
%-9s

Section 4.4: Conditional Execution with Methods

Definitions

Definitions:

  • Precondition
  • Postcondition

Basically, this section addresses: how do we ensure certain conditions are met before/after we run a method?

Exceptions:

  • Occur at runtime, not compile time
  • Previously, saw exceptions with scanner (nextInt(), not an int)

Assessment questions:

When would you see an exception?

  • Run time
  • Compile time

When would you see a logic error?

  • Run time
  • Compile time

When would you see a syntax error?

  • Run time
  • Compile time

Functions (analogy):

  • Factorial function: can compute 0!, 1!, 2!, etc
  • Cannot ocmpute negative factorial, so return undefined
  • Mathematical approach: exceptions are definitions, rules that they can define

Documentation:

  • Tell the user how to use it

Creating exceptions:

  • exceptions are objects
  • Pieces of grouped data/instructions
  • Need to create new exceptions before we can throw them
  • When we throw an exception, it stops the code
  • We also want to add comments! and a useful exception message!

Similar concept (language): assertions

  • C and C++, Python, assert(True)

Revisiting return values: example

  • New application of conditional logic to comparison operators:
  • Example of overloading (int and float)
  • If statement for ints, etc.
  • more templating: again, comes down to understanding what kind of control structure you need
def method() {
  if( x > y) {
    return x
  }
  return y
}

Revisiting return values: another example

  • String: find particular index of particular character
  • built-in String method, indeOf
  • r = s.indexOf('r')
  • make our own static method: myIndexOf
  • called like, r = myIndexOf('r',s)
  • How to locate a character in a string?
    • Can loop through each char of string (i in str length)
    • Then, can use charAt to see if this char is our char
  • Note on why not static method:
    • static method doesn't remember our place
    • if we wanted to say, "find the next r," we'd have to pick up where we left off
    • that means, saving a piece of data, which means, we can't use static method
  • Implement return method
    • return our char index
    • else, what to do if char not found?
    • convention: return -1 (or, 999,999)
  • Scope:
    • allows us to say, when we get to return, we can drop everything and leave, everything will be cleaned up

String index and bounds:

  • index of string of N characters: starts at 0, runs to N-1
  • If we access a string at index N, Java will raise an exception
  • Exception won't happen until runtime - that's when Java will know string length, and will know string is not long enough

Following logical branches:

  • Example of program with nested if/else if/else if
  • if you have a return type defined in the method header (e.g., string), that means you have to have a return statement, no matter what, for all cases (or, throw an exception)
  • Can eliminate some code if we assume we know the SAT score is in the range 600-2400
  • Assuming is BAD!!!
if(totalSAT<600 || totalSAT > 2400 ) {
    raise IllegalArgumentException
} else {
    ...
}

Section 4.5: BMI Study

Definitions

Definitions:

  • Cohesion
  • Coupling
  • Chaining

Material

BMI:

  • Calculation based on input values (weight, height)
  • Iterative enhancement: one thing at a time
    • Compute results for one person (no structure)
    • Write program for 2 people (no structure)
    • Finally, assemble well-structured program

One person unstructured:

  • height and wieght, read in
  • Calulate BMI from that
  • One line at a time, get x, print x, get y, print y, calc z, print z
  • use printf
  • use conditional to classify weight status
  • again, one line after another

Two person unstructured:

  • to handle a second person, eneed to prompt for both people's data, then do calcs, then print results all at onc
  • New structure:
    • chunk of code for intro
    • chunk of code for person 1
    • chunk of code for person 2
    • print person 1
    • print person 2

Nowmove on to a more structured solution:

  • giveIntro
  • bm1 = getbmi()
  • bm2 =getbmi()
  • reportresults(bm1,bm2)

Heuristics: 1. Each method should have a coherent set of responsibilities 2. No one method should do too large a share of the overall task 3. Coupling and dependencies between methods should be minimized 4. The main method should be a concise summary of the overall program 5. Data should be owned at the lowest possible level (abstract away detail and complexity)

Quotes

Murphy's Law:

  • If the user can do something wrong, they will do something wrong

Hanscombe's Law:

  • Never attribute to malice what is equally attributable to stupidity

Chapter 4: Summary

Deliverables

If/else:

  • Syntax
  • Following execution-branching
  • Relational operators and true/false conditions
  • Revisiting operator precedence/evaluation order
  • Patterns for designing nested if/else structures, depending on how many conditions may apply
  • Box diagram representation
  • String equality
  • Reducing complexity: reuse code for nested if statements

Cumulative algorithms:

  • Connecting loops with algorithms
  • Roundoff error - source, how to deal (equality)

Text processing:

  • Chars and strings
  • Chars and ints
  • printf

Conditional execution with methods

  • When you use this
  • Mathematics analogy - definitions, we define our own rules, define how things work and when
  • Documentation - have to tell the user how to use it
  • Exceptions - have to deal with potential problems, both internally and from users
  • In-class example to revisit return values, example of overloading, if statements
  • More templating - comes down to understanding what kind of control structure you need
  • Static methods
  • String index and bounds, possible string bounds exceptions
  • Following logical branches
  • How to eliminate code with exceptions/assertions

Heuristics: 1. Each method should have coherent set of responsibilities 2. No one method should do too large a share of the overall task 3. Coupling and dependencies between methods should be minimized 4. The main method should be a concise summary of the overall program 5. Data should be owned at the lowest possible level (abstract away detail and complexity)

Heuristics

1. Each method should have a coherent set of responsibilities

2. No one method should do too large a share of the overall task

3. Coupling and dependencies between methods should be minimized

4. The main method should be a concise summary of the overall program

5. Data should be owned at the lowest possible level (abstract away detail and complexity)

Chapter 4 Code

Lecture Code

Hailstone sequence

  • odd/even Integer sequence
  • map for loop (1 to N) onto hailstone sequence using formula
  • if/else to check for odd/even
  • uses printf
  • uses static methods

Worksheet Code

Section 4.3: Using (and Cracking) the Caesar Cipher

  • Automate cracking the Caesar cipher
  • Last time: learned how to manipulate chars using integers
  • This time: we want to automate cracking the Caesar cipher
  • Strategies? Can look at letter frequencies
  • Table of letter frequenceis in English language
  • We are going to calculate letter frequencies in the ciphertext, and keep track of which letter is most frequent
  • Use this to suggest/pick a "most likely" substitution and see if it works

Chapter 4 Homework

HW Summary

(Recommended) Self-check problems: #1, #5, #6, #12, #19, #21, #28

(Required) Exercises: #1, #5, #9,

(Required) Projects: #6 (poss. modification to CC numbers)

HW Details

Self-check:

  • 1 - translating english into boolean expressions
  • 5, 6 - if/else mystery
  • 12 - improving poorly structured code to avoid redundancy
  • 19 - comparing floats
  • 21 - check if string starts with capital
  • 28 - add exceptions to quadratic equation code

Exercises:

  • 1 - fractionSum() method
  • 5 - custom pow() method
  • 9 - prompt for integers, sum even no.s, largest even no. typed

Projects:

  • 6 - check digit (7th digit is checksum of first 6)

Chapter 4 Goodies

Puzzle 4

Block cryptogram:

MVBY ZJVY LHUK ZLCL UFLH YZHN VVBY MVYL MHAO LYZZ LAMV 
YAOV UAOP ZSHU KHUL DUHA PVUJ VUJL PCLK PUSP ILYA FHUK 
KLKP JHAL KAVA OLWY VWVZ PAPV UAOH AHSS TLUH YLJY LHAL 
KLXB HS

To help them out, start it with the word "THE".

Challenge cryptogram: (+8)

Iuwvo(w|pmz(x}jtqk(j}qtlqvo{(qv(i(kmz|iqv(|w?v4(?pqkp(nwz(uiv(zmi{wv{(q|(?qtt(jm(xz}lmv|(|w(zmnziqv(nzwu(umv|qwvqvo4(ivl(|w(?pqkp(Q(?qtt(i{{qov(vw(nqk|q|qw}{(vium4(|pmzm(q{(wvm(ivkqmv|t(kwuuwv(|w(uw{|(|w?v{4(ozmi|(wz({uittB(|w(?q|4(i(?wzspw}{mC(ivl(qv(|pq{(?wzspw}{m(?i{(jwzvC(wv(i(li(ivl(li|m(?pqkp(Q(vmml(vw|(|zw}jtm(u{mtn(|w(zmxmi|4(qvi{u}kp(i{(q|(kiv(jm(wn(vw(xw{{qjtm(kwv{my}mvkm(|w(|pm(zmilmz4(qv(|pq{({|iom(wn(|pm(j}{qvm{{(i|(itt(m~mv|{C(|pm(q|mu(wn(uwz|itq|(?pw{m(vium(q{(xzmnq€ml(|w(|pm(pmil(wn(|pq{(kpix|mz6

Laws and Razors

Murphy's Law: If the user can' do something wrong, they will do something wrong

Occam's Razor: A hypothesis should not be any more complicated than is necessary. (Or: Simple hypotheses are the most plausible.)

Hanlon's Razor: Never attribute to malice what is equally attributable to stupidity.

Flags