{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# Notes7a - Chapter 7 More Flow of Control Goals To analyze...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 7 More Flow of Control Goals: To analyze the use of Boolean expressions To introduce the notion of enumerated types To explore the switch statement as an alternative to multiway if-else statements To view the conditional statement as a alternative to a simple if-else statement To examine the forstatement as a looping option To demonstrate the design of good nested loops Precedence Rules for Boolean Expressions With the addition of Boolean operators, the precedence rules that C++ uses to evaluate expressions become more complex. Parentheses still take the highest precedence Multiplication, division, and modulus come second. Addition and subtraction take the next precedence. Orderrelated inequality operators (<, >, <=, >=) are next. The pure equality/inequality (==, !=) operators are next. The Boolean AND operator (&&) takes the next precedence. The Boolean OR operator (||) takes the lowest precedence. Precedence ties are still handled in lefttoright fashion. CS 140 Chapter 7 Page 2 Precedence Rules Examples int x = 7, if (x == y cout << else cout << y = 7, z = 7; == z) "YES"; "NO"; int a = if (a < cout else cout 5, b = 4, c = 3; b < c) << "YES"; << "NO"; Output: NO The left equality is checked and evaluates to true (numerical 1), which is not equal to the zvalue! CS 140 Chapter 7 Output: YES The left inequality is checked and evaluates to false (numerical 0), which is less than the cvalue! Page 3 Boolean Expressions ShortCircuit Evaluation of && When a Boolean expression using the && operator is evaluated, the first subexpression is evaluated first. if it evaluates to false, then the second subexpression is ignored. if ((x z = else z = != 0) && (y/x > 1)) 100; -1; When this code segment is encountered and x's value is zero, z will be assigned either the value 100 or the value 1. if ((y/x > 1) && (x != 0)) z = 100; else z = -1; Chapter 7 Page 4 When this code segment is encountered and x's value is zero, the program crashes due to the attempt to divide by zero! CS 140 Boolean Expressions ShortCircuit Evaluation of || When a Boolean expression using the || operator is evaluated, the first subexpression is evaluated first. if it evaluates to true, then the second subexpression is ignored. if ((ct == 0) || (total/ct > 70)) cout << "NO PROBLEMO"; When this code segment is encountered and ct's value is zero, the program crashes due to the attempt to divide by zero! CS 140 When this code segment is encountered and ct's value is zero, the message is output. if ((total/ct > 70) || (ct == 0)) cout << "NO PROBLEMO"; Chapter 7 Page 5 Enumerated Types #include <iostream> using namespace std; To enhance the readability of one's code, a programmer can define an enumerated type, which consists of a set of integer constants. enum MonthNumber { JANUARY = 1, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }; void main() { MonthNumber monthCount = JANUARY; double monthlyRate = 12.34, totalCost = 0.0; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Computing Annual Costs:\n\n"; while (monthCount <= DECEMBER) { totalCost += monthlyRate; monthCount = MonthNumber(monthCount + 1); } cout << endl << endl << "Total: \$" << totalCost << endl << endl; return; } CS 140 Chapter 7 Page 6 switch Statements C++ switch statements provide a simple alternative to the use of convoluted nested if-else statements. if (month == 2) { if (year % 4 == 0) daysInMonth = 29; else daysInMonth = 28; } else if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) daysInMonth = 30; else daysInMonth = 31; CS 140 switch (month) { case 2: { if (year % 4 == 0) daysInMonth = 29; else daysInMonth = 28; break; } case 4: case 6: case 9: case 11: { daysInMonth = 30; break; } default: { daysInMonth = 31; break; } } Chapter 7 Page 7 Conditional Statements C++ conditional statements provide a concise alternative to the use of relatively simple if-else statements. if (val > 0) cout << "GOOD"; else cout << "BAD"; (val > 0) ? (cout << "GOOD") : (cout << "BAD"); if (year % 4 == 0) daysInMonth = 29; else daysInMonth = 28; daysInMonth = (year % 4 == 0) ? 29 : 28; CS 140 Chapter 7 Page 8 #include <iostream> using namespace std; The break statements void main() ensure that the switch { statement is exited once the char letter; appropriate case is handled. bool gotAVowel = false; do Without the break { cout << "Please enter a letter: "; statements, all cases might cin >> letter; execute. switch(letter) { case 'a': case 'A': cout << "Apple\n"; gotAVowel = true; break; case 'e': case 'E': cout << "Egg\n"; gotAVowel = true; break; case 'i': case 'I': cout << "Iodine\n"; gotAVowel = true; break; case 'o': case 'O': cout << "Oval\n"; gotAVowel = true; break; case 'u': case 'U': cout << "Upper\n"; gotAVowel = true; break; default: cout << "That is not a vowel. Please try again.\n"; } The default case is executed if }while(!gotAVowel); no other case value matches. } CS 140 Chapter 7 Page 9 The for Statement The C++ for statement is designed to facilitate looping when the control of the loop contains three standard features: An initialization action that is performed just before the loop is started the first time. A Boolean expression that is checked just before entering the loop at each iteration. An update action that is performed just after each iteration of the loop is completed. for (initAction; booleanExp; updateAction) bodyOfLoop CS 140 Chapter 7 Page 10 A forloop Example #include <iostream> using namespace std; enum Day { SUNDAY = 1, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; const double PAY_RATE = 5.15; double retrieveHoursWorkedForDay(Day dayOfTheWeek); void main() { Day dayOfWeek; double hoursWorked; double payForWeek = 0.0; dayOfWeek is initialized to SUNDAY when the for loop is first encountered. This inequality is checked just before the body of the loop is entered (or reentered). for (dayOfWeek = SUNDAY; dayOfWeek <= SATURDAY; dayOfWeek = Day(dayOfWeek + 1)) { hoursWorked = retrieveHoursWorkedForDay(dayOfWeek); (dayOfWeek == SUNDAY) ? (payForWeek += 1.5 * hoursWorked * PAY_RATE) : This assignment statement (payForWeek += hoursWorked * PAY_RATE); is executed right after } cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); } CS 140 Chapter 7 each execution of the body of the loop. cout << endl << endl << "Your Pay For The Week Is \$" << payForWeek << endl << endl; Page 11 double retrieveHoursWorkedForDay(Day dayOfTheWeek) { double hours; cout << "Enter the hours switch (dayOfTheWeek) { case SUNDAY: cout << case MONDAY: cout << case TUESDAY: cout << case WEDNESDAY: cout << case THURSDAY: cout << case FRIDAY: cout << case SATURDAY: cout << } cin >> hours; return hours; } worked on "; "Sunday: "Monday: "Tuesday: "Wednesday: "Thursday: "Friday: "Saturday: "; "; "; "; "; "; "; break; break; break; break; break; break; break; CS 140 Chapter 7 Page 12 Another forloop Example #include <iostream> using namespace std; void main() { char party; int leapYear; int elephants = 0; int donkeys = 0; for (leapYear = 2000; leapYear >= 1916; leapYear -= 4) { cout << "Which party won in " << leapYear << "? (Enter R or D) "; cin >> party; (party == 'R') ? elephants++ : donkeys++; } (elephants > donkeys) ? (cout << "\nRepublicans Rule!\n\n") : ((donkeys > elephants) ? (cout << "\nDemocrats Dominate!\n\n") : (cout << "\nTiebreaker Time!\n\n")); return; } CS 140 Chapter 7 Page 13 Nested forloops #include <iostream> using namespace std; void main() { int iterationNbr, repetitionNbr, indentSpaceNbr; for (iterationNbr = 1; iterationNbr <= 25; iterationNbr++) for (repetitionNbr = 1; repetitionNbr <= 1000; repetitionNbr++) { cout << '\r'; for (indentSpaceNbr = 1; indentSpaceNbr <= iterationNbr; indentSpaceNbr++) cout << ' '; cout << "HAPPY NEW YEAR!"; } cout << endl << endl; return; } CS 140 Chapter 7 Page 14 ...
View Full Document

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern