|
|
| Line 13: |
Line 13: |
| =Chapter 4: Conditional Execution= | | =Chapter 4: Conditional Execution= |
|
| |
|
| Sections:
| | [[CSC 142/Chapter 4]] |
| | |
| 4.1 If/else statements
| |
| | |
| 4.2 Cmulative 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==
| |
| | |
| 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"
| |
| | |
| <code>if( a == 24 )</code> vs. <code>int a = 24;</code>
| |
| | |
| 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:
| |
| | |
| <pre>
| |
| if( condition1 ) {
| |
| ...
| |
| } else if( condition2 ) {
| |
| ...
| |
| } else if( condition3 ) {
| |
| ...
| |
| }
| |
| </pre>
| |
| | |
| Multiple conditions can be true:
| |
| | |
| <pre>
| |
| if( condition1 ) {
| |
| ...
| |
| }
| |
| if( condition2 ) {
| |
| ...
| |
| }
| |
| if( condition3 ) {
| |
| ...
| |
| }
| |
| </pre>
| |
| | |
| 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)
| |
| | |
| ==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
| |
| | |
| <pre>
| |
| abs(A-B) < 0.01
| |
| </pre>
| |
| | |
| ==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
| |
| * <code>%d</code> digit, f for float, etc.
| |
| * Table of common print formats
| |
| | |
| <pre>
| |
| %d
| |
| %8d
| |
| %-6d
| |
| | |
| %f
| |
| %.2f
| |
| %16.2f
| |
| | |
| %s
| |
| %8s
| |
| %-9s
| |
| </pre>
| |
| | |
| ===Handout: Caesar Cipher===
| |
| | |
| Cracking the Caesar cipher: letter frequencies, and also brute-forcing
| |
| | |
| ==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
| |
| | |
| <pre>
| |
| def method() {
| |
| if( x > y) {
| |
| return x
| |
| }
| |
| return y
| |
| }
| |
| </pre>
| |
| | |
| 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!!!
| |
| | |
| <pre>
| |
| if(totalSAT<600 || totalSAT > 2400 ) {
| |
| raise IllegalArgumentException
| |
| } else {
| |
| ...
| |
| }
| |
| </pre>
| |
| | |
| ==Section 4.5: BMI Study==
| |
| | |
| 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
| |
|
| |
|
| =Flags= | | =Flags= |
|
| |
|
| [[Category:Teaching]] | | [[Category:Teaching]] |