Class Note for EECS 168 at KU
Popular in Course
Popular in Department
This 28 page Class Notes was uploaded by an elite notetaker on Friday February 6, 2015. The Class Notes belongs to a course at Kansas taught by a professor in Fall. Since its upload, it has received 17 views.
Reviews for Class Note for EECS 168 at KU
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 02/06/15
More on Flow of Control Read Chpt 3 Flow of Control Order in which statements in program are executed Altering Flow of Control using 0 Branching if elsestatement nested if else statement switch 0 Repetition While100p doWhileloop for100p o doWhile statement More on Boolean Expressions 0 Either true or false 0 Formed by using relational arithmetic and logical operators Arithmetic Operators Relational Operators Boolean Operators ampamp Compound Expression Expression formed by using the above Boolean and or relational operators Q How can we evaluate the following expressions xlgt2xllt3 x2gt8yzampampx0 Confusing Try to avoid complicate compound expression In order to evaluate a compound expression one must know the order of precedence and operator hierarchy Precedence Rules Unary operators Highest Arithmetic operators Arithmetic operators Relational operators lt gt lt gt Comparison operators Boolean operator ampamp Boolean operator Lowest Order of Evaluation Right to left for unary operators and left to right for binary operators Order of Precedence If parentheses are omitted from boolean expressions the default precedence of operations is 0 Perform unary operations such as l 0 Perform arithmetic operations next 0 Perform relational operations lt gt lt gt next 0 Perform logical operations ampamp and H last Examples 1 The expression x1gt2Hx1lt3 is same as X 1 gt 2 H X 1 lt 3 2 The expression x2gt8yzampampxl0 is same as X 2 gt 8 H Y Z Z ampamp X l 0 ShortCircuit Evaluation in C In evaluating a compound Boolean expression E formed by several subexpressions joined by the Boolean operators ampamp and H some languages including C and C do not require a complete evaluation of all the subexpressions As soon as the value of the compound expression is determined all the remaining subexpressions will be skipped Some programming languages such as Pascal use complete evaluation Shortcircuit evaluation can be used to prevent run time errors Examples 1 If x is negative the value of the expression x gt 0 ampamp ygt 1 can be determined by evaluating only x gt 0 The value of y gt 1 is not evaluated 2 Consider this if statement if num O ampamp sum num gt 70 do something Observe that if num 0 sum num will result in a runtime error division by zero Type bool and int Recall that in C one can convert an int type to a bool type and vice versa Conversion between bool and int types y bool y 7E 0 true 1 gt gt 0 false 0 Example Consider the expression speed gt limit It is false when speed 80 and limit 70 It is true when speed 65 and limit 7 O Q What if we mistakenly wrote speed gt limit Recall that any nonzero integer has Boolean value true Hence the above expression will be evaluated as follows speed speed is true hence speed is false speed gt limit lspeed is O 0 gt 70 is false Observe that independent of speed speed gt limit will always be false Remark Avoid using convert the expression into an equivalent expression without Example speed gt limit is the same as speed S time Multiway Branching Recall that a simple if else statement will allow us to choose between two alternatives 2way branching if boolean expression true statements else false statements Q How does one choose when there are more than two alternatives Using nested if else statements statements in if else statement are themselves if else statements Example Design an ifelse statement to warn a driver when fuel is low but tells the driver to bypass stops if the fuel is close to full Otherwise there should be no output if fuel gauge lt 3A then if fuel gauge lt 1A then issue a warning else output fuel gt 3A don39t stop C code if fuelgaugereading lt 075 if fuelgaugereading lt 025 cout ltlt quotFuel very low Cautionnquot else cout ltlt quotFuel over 34 Don39t stop nownquot Q What is the output if fuelgaugereading is 05 Remarks 0 It will compile and run but it will not generate the desired output 0 We have a dangling else problem should the elsestatement be paired with the first or second ifstatement 0 An elsestatement will always be paired with the nearest previous if statement For above example it Will be executed as if fuelgaugereading lt 075 if fuelgaugereading lt 025 cout ltlt quotFuel very lOW Cautionnquot else cout ltlt quotFuel over 34 Don39t stop nownquot Remedy Use braces Example Display 34 on P 120 include lti0streamgt using namespace std int main double fuelgaugereading cout ltlt quotEnter fuel gauge reading quot cin gtgt fuelgaugereading cout ltlt quotFirst with bracesnquot if 1e1gaugereading lt 07 5 if fuelgaugereading lt 025 cout ltlt quotFuel very lOW Cautionnquot else cout ltlt quotFuel over 34 Don39t stop n0Wnquot cout ltlt quotNow Without bracesnquot if 1e1gaugereading lt 075 if fuelgaugereading lt 025 cout ltlt quotFuel very low Cautionnquot else cout ltlt quotFuel over 34 Don t stop n0wnquot return 0 Input 05 Output Enter fuel gauge reading 05 First With braces New Without braces Fuel over 34 Don t stop now Multiway Branching Syntax if BooleanEXpressi0nl Statementl else if BooleanEXpressi0n2 Statement2 else if BooleanEXpressionn Statement n else StatementF0rAllOtherPossibilities Examples 1 Consider the previous grade example if score lt 60 cout ltlt quot student gets F gradequot ltlt endl else if score lt 7 O cout ltlt quot student gets D gradequot ltlt endl else if score lt 80 cout ltlt quot student gets C gradequot ltlt endl else if score lt 90 cout ltlt quot student gets B gradequot ltlt endl else cout ltlt quot student gets A gradequot ltlt endl 2 Another nested if else example if temperature lt 10 ampamp da Mon cout ltlt Stay home else if temperature lt 10 day Mon cout ltlt Call work else if temperature lt 0 temp gt 10 cout ltlt Dress warm else temp gt 0 cout ltlt Work hard and play hard 10 Enumerated Type 0 An enumerated type is a type that allows us to de ne any ordered group of identi ers Whose values are of type int 0 An enumerated type is like a list of declared integer constants except it has a type name associated With it 0 An enumerated type is just an ordered list of integer constants in disguise 0 An enumerated type is constructed using the keyword enum o The identi ers in an enumerated type are ordered and have int values If they are not speci ed they Will be ordered assigned 0 l 0 We can assign any int value to an identi er using identifier intvalue Once an identi er is assigned an intvalue subsequent identi ers Will be assigned intvalue l intvalue 2 or until an identi er is assigned a different int value using the same mechanism 0 The constants identi ers that make up the type can not be shared ll Enumerated Type Syntax enum typename identi erlist identi erlist is a list of identi ers with or without an assigned integer constant Examples enum weekday Mon Tue Wed Thu Fri Mon gets 0 Tue gets 1 Wed gets 2 Thu gets 3 Fri gets 4 weekday day day can take on any value in weekday day Tue if day gt O This is true Example enum weekday Mon 18 Tue Wed 1 Thu Fri 5 Mon gets 18 Tue gets l7 Wed gets 1 Thu gets 2 Fri gets 5 Example This is wrong enum color red white blue orange yellow enum fruit apple orange strawberry 12 Another C construct for multiway branching The Switch Statement Syntax switch ControllingEXpression case Constant1 StatementSequence1 break case Constant2 StatementSequence2 break case Constantn StatementSequencen break default DefaultStatementSequence break 13 Example switch vehicleclass case 1 cout ltlt passenger car ltlt endl toll 050 break case 2 cout ltlt Bus toll 150 break case 3 cout ltlt Truck toll 200 break default cout ltlt Unknown vehicle class l4 More on Switch The value of the controlling expression must be of integer int bool char or enumerated type The value returned is compared to the constant values after each quotcase statement When a match is found the code for that case is used Every casestatement must end with a break statement When a breakstatement is executed the switchstatement will be terminated and execution will resume at the statement immediately following the switchstatement If a casestatement does not end with a break statement program execution will continue to the next casestatement Omitting a break statement allows the execution of multiple case labels for a section of code Example Runs the same code for either 39A39 or 39a39 case 39A39 case 39a39 cout ltlt quotExcellentquot break If no case label has a constant that matches the controlling expression the statements following the default label are executed When none of the caseconstant is matched the defaultstatement will be executed 15 0 When none of the caseconstant is matched and there is no defaultstatement the switchstatement will not be executed Example enum weekday Mon Tue Wed Thu Fri weekday day switch day case Mon cout ltlt Monday break case Tue cout ltlt Tueday break case Wed cout ltlt Wednesday break case Thu cout ltlt Thursday break case Fri cout ltlt Friday break default cout ltlt Weekend 16 Example include ltiostreamgt using namespace std int main char grade cout ltlt quotEnter your midterm grade and press return quot cin gtgt grade switch grade case 39A39 cout ltlt quotExcellent quot ltlt quotYou need not take the nalnquot break case 39B39 cout ltlt quotVery good quot grade 39A39 cout ltlt quotYour midterm grade now is quot ltlt grade ltlt endl break case 390 cout ltlt quotPassingnquot break case 39D39 case 39F39 cout ltlt quotNot good quot ltlt quotGo studynquot break default 17 cout ltlt quotThat is not a possible gradenquot cout ltlt quotEnd of programnquot return 0 Primality Testing Program Input A positive integer n 1 S n S 100 Output Inform user on whether 11 is prime Approach Check for prime factors up to the square root of the input number If none is found then the number is prime include ltiostreamgt using namespace std int main int number bool prime true Read input number cout ltlt quotEnter a number between 1 100 quot cin gtgt number Check input is valid if number lt 1 number gt 100 cout ltlt quotError Number is out of rangenquot 18 return 1 if number 1 prime false if number gt 2 ampamp number 2 0 prime false if number gt 3 ampamp number 3 0 prime false if number gt 5 ampamp number 5 0 prime false if number gt 7 ampamp number 7 0 prime false Print output if prime cout ltlt quotNumber quot ltlt number ltlt quot IS primenquot else cout ltlt quotNumber quot ltlt number ltlt quot is NOT primenquot return 0 l9 More on Loop Structures WhileLoop while booleanexpression loop condition statementl loop body statement2 statementn DoWhile Loop do statementl loop body statement2 statementn while booleanexpression loop condition Difference between while and do while loops 0 A whileloop checks the Boolean expression at the beginning of the loop but a dowhile loop checks the Boolean expression at the end of the loop 0 A whileloop might never be executed but a do while loop is always executed at least once 20 Example Computing the sum of 1 2 100 Using while100p int sum 0 int num 1 While num lt 100 sum sum num num Using d0while100p int sum 0 int num 1 do sum sum num num While num lt 100 Another 100p mechanism in C ForStatement forloop 0 Designed for common tasks such as adding numbers in a given range 0 Is sometimes more convenient to use than a While loop 0 Does not do anything a While loop cannot do 21 Using for100p Syntax for InitialAction BooleanEXpression UpdateAction BodyStatement Or for InitialAction BooleanEXpression UpdateAction statementl statement2 statementn Remark The body of a forloop can be 0 A single statement 0 A compound statement enclosed in braces Example int sum O for int num l num lt 100 num sum sum num num is a local var in forbody 22 Interpretation for int num l num lt 100 num l initialization Boolean expression update Initialization Create a variable num of type int and initialize it With l Boolean expression Continue to iterate the body as long as num lt 100 Update Increment n by one after each iteration More Examples 1 forn lnlt lOnn2 2 forn0 ngtlOO nn7 3 for double X powy30 X gt 20 X sqrtX 4 Placing a semicolon after the parentheses of a for loop creates an empty statement as the body of the loop forint count 1 count lt 10 count cout ltlt quotHellonquot cout is not part of the loop 23 Defn Factorial function 0 l n nnln22l int factorialint n int product 1 int i l i is a local variable in factorial function for i n i gt 1 i product product i return product Q What if we execute the following code int factorialint n int product 1 int i l for i n i gt 1 i product product i return product Remark This is legal However the null statement Will be executed n times and product 1 Will be returned 24 Choosing a Loop Structure 0 Whileloops are used when the loop may not run 0 Dowhile loops are used when the loop must always run at least once 0 Forloops are used when using a variable changed by equal amounts each time the loop iterates More on Increment amp Decrement Operators n Use value of n then 11 11 1 n Compute n n l and use value of new 11 n Use value of n then 11 n l n Compute n n l and use value of new 11 Remark Although these operators can be used in any expression Example 20num they can only be applied to single variable illegal to use xy Nested Loops Statements in a loop body can be a loop statement or function that contains another loop A break statement will terminate the execution of the current loop statement and execution will continue with the statement immediately following the loop statement Designing Loop Statements 0 Initializing statements 0 Body 0 Conditions for ending the loop 25 Testing Loop Statements Each loop should be tested With a set of values for correctness such that it Will result in 0 Zero iterations o Exactly one iteration o The maximum number of iterations 0 One less than the maximum number of iterations Debugging Loop Statements 0 A common loop error is the off by one error 0 The error is either running the loop one too many times or one too few times 0 A second error is an in nite loop 0 If your error isn t one of the common errors more sophisticated testing Will be required 0 You can use a debugger and examine the loop variables or use output statements to print out these variables Terminating a Loop Statement There are four common methods for terminating a loop 1 List headed by size know the number of iterations 2 Ask before iterating 3 List ended by sentinel value 4 Running out of input End of le 26 List Headed by Size Example int sum O for int count 1 count lt thismany count cm gtgt next sum sum next Ask Before Iterating Example sum O cout ltlt Are there numbers in the list Y ltcrgt for yes N ltcrgt for N0n char ans cin gtgt ans While an Y M an y cout ltlt Enter number cin gtgt number sum sum number cout ltlt Are them any more numbers ltlt Y ltcrgt for yes N ltcrgt for N0n cin gtgt ans 27 List Ended by Sentinel Value Use a nondata value is to be detected to end input Example cout ltlt Enter a list of nonnegative integers n ltlt Terminate the list with a negative numbern sum O cin gtgt number While number gt 0 sum sum number cin gtgt number 28
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'