chapter 3 more flow of control goals: to analyze the use of boolean expressions to analyze the use...

12
Chapter 3 Chapter 3 More Flow of Control More Flow of Control Goals: Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated types To introduce the notion of enumerated types To explore the To explore the switch switch statement as an alternative to multiway statement as an alternative to multiway if-else if-else statements statements To examine the To examine the for for -statement as a looping option -statement as a looping option To demonstrate the design of good nested loops To demonstrate the design of good nested loops To view the conditional statement as a alternative to a simple To view the conditional statement as a alternative to a simple if-else if-else statement statement

Upload: cuthbert-dennis

Post on 17-Jan-2016

240 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3More Flow of ControlMore Flow of ControlGoals:Goals:

• To analyze the use of Boolean expressionsTo analyze the use of Boolean expressions

• To introduce the notion of enumerated typesTo introduce the notion of enumerated types

• To explore theTo explore the switch switch statement as an alternative statement as an alternative to multiwayto multiway if-else if-else statementsstatements

• To examine theTo examine the for for-statement as a looping option-statement as a looping option

• To demonstrate the design of good nested loopsTo demonstrate the design of good nested loops

• To view the conditional statement as a alternative To view the conditional statement as a alternative to a simpleto a simple if-else if-else statementstatement

Page 2: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 22

Precedence Rules for Boolean Precedence Rules for Boolean ExpressionsExpressions

With the addition of Boolean operators, the precedence With the addition of Boolean operators, the precedence rules that C++ uses to evaluate expressions become rules that C++ uses to evaluate expressions become more complex.more complex.• Parentheses still take the highest precedenceParentheses still take the highest precedence• Multiplication, division, and modulus come second.Multiplication, division, and modulus come second.• Addition and subtraction take the next precedence.Addition and subtraction take the next precedence.

• Precedence ties are still handled in left-to-right Precedence ties are still handled in left-to-right fashion.fashion.

• Order-related inequality operators (<, >, <=, >=) are Order-related inequality operators (<, >, <=, >=) are next.next.• The pure equality/inequality (==, !=) operators are The pure equality/inequality (==, !=) operators are next.next.• The Boolean AND operator (&&) takes the next The Boolean AND operator (&&) takes the next precedence.precedence.• The Boolean OR operator (||) takes the lowest The Boolean OR operator (||) takes the lowest precedence.precedence.

Page 3: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 33

Precedence Rules ExamplesPrecedence Rules Examples

int x = 7, y = 7, z = 7;int x = 7, y = 7, z = 7;if (x == y == z)if (x == y == z) cout << “YES”;cout << “YES”;elseelse cout << “NO”;cout << “NO”;

int a = 5, b = 4, c = 3;int a = 5, b = 4, c = 3;if (a < b < c)if (a < b < c) cout << “YES”;cout << “YES”;elseelse cout << “NO”;cout << “NO”;

Output: NOOutput: NO

The left equality is The left equality is checked and evaluates to checked and evaluates to true (numerical 1), which true (numerical 1), which is is notnot equal to the z-value! equal to the z-value!

Output: NOOutput: NO

The left equality is The left equality is checked and evaluates to checked and evaluates to true (numerical 1), which true (numerical 1), which is is notnot equal to the z-value! equal to the z-value!

Output: YESOutput: YES

The left inequality is The left inequality is checked and evaluates to checked and evaluates to false (numerical 0), which false (numerical 0), which

isis less than the c-value! less than the c-value!

Output: YESOutput: YES

The left inequality is The left inequality is checked and evaluates to checked and evaluates to false (numerical 0), which false (numerical 0), which

isis less than the c-value! less than the c-value!

Page 4: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 44

Boolean Expressions -Boolean Expressions -Short-Circuit Evaluation of Short-Circuit Evaluation of &&&&

When a Boolean expression using theWhen a Boolean expression using the && && operator is operator is evaluated, the first subexpression is evaluated first. if evaluated, the first subexpression is evaluated first. if it evaluates toit evaluates to false false, then the second subexpression is , then the second subexpression is ignoredignored..

if ((x != 0) && (y/x > 1))if ((x != 0) && (y/x > 1)) z = 100;z = 100;elseelse z = -1;z = -1;

if ((y/x > 1) && (x != 0))if ((y/x > 1) && (x != 0)) z = 100;z = 100;elseelse z = -1;z = -1;

When this code When this code segment is segment is

encountered andencountered and x x’s ’s value is zero,value is zero, z z will be will be

assigned either the assigned either the value 100 or the value -value 100 or the value -

1.1.When this code segment When this code segment is encountered andis encountered and x x’s ’s

value is zero, the value is zero, the program crashes due to program crashes due to the attempt to divide by the attempt to divide by

zero!zero!

Page 5: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 55

Boolean Expressions -Boolean Expressions -Short-Circuit Evaluation of Short-Circuit Evaluation of ||||

When a Boolean expression using theWhen a Boolean expression using the || || operator is operator is evaluated, the first subexpression is evaluated first. if evaluated, the first subexpression is evaluated first. if it evaluates toit evaluates to true true, then the second subexpression is , then the second subexpression is ignoredignored..

if ((ct == 0) || (total/ct > 70))if ((ct == 0) || (total/ct > 70)) cout << “NO PROBLEMO”;cout << “NO PROBLEMO”;

if ((total/ct > 70) || (ct == 0))if ((total/ct > 70) || (ct == 0)) cout << “NO PROBLEMO”;cout << “NO PROBLEMO”;

When this code When this code segment is segment is

encountered andencountered and ctct’s value is zero, ’s value is zero,

the message is the message is output.output.

When this code When this code segment is segment is

encountered andencountered and ctct’s value is zero, ’s value is zero,

the program the program crashes due to the crashes due to the

attempt to divide by attempt to divide by zero!zero!

Page 6: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 66

Enumerated Enumerated TypesTypes

To enhance the readability of one’s code, To enhance the readability of one’s code, a programmer can define an a programmer can define an enumerated enumerated typetype, which consists of a set of integer , which consists of a set of integer constants.constants.#include <iostream>

using namespace std;

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;}

Page 7: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 77

switchswitch Statements StatementsC++C++ switch switch statements provide a simple alternative to statements provide a simple alternative to the use of convoluted nestedthe use of convoluted nested if-else if-else statements.statements.

if (month == 2)if (month == 2){{ if (year % 4 == 0)if (year % 4 == 0) daysInMonth = 29;daysInMonth = 29; elseelse daysInMonth = 28;daysInMonth = 28;}}else if ((month == 4) ||else if ((month == 4) || (month == 6) ||(month == 6) || (month == 9) ||(month == 9) || (month == 11)) (month == 11)) daysInMonth = 30;daysInMonth = 30;elseelse daysInMonth = 31;daysInMonth = 31;

switch (month)switch (month){{ case 2: {case 2: { if (year % 4 == 0)if (year % 4 == 0) daysInMonth = 29;daysInMonth = 29; elseelse daysInMonth = 28;daysInMonth = 28; break;break; }} case 4:case 4: case 6:case 6: case 9:case 9: case 11: { daysInMonth = 30; break; } case 11: { daysInMonth = 30; break; } default: { daysInMonth = 31; break; }default: { daysInMonth = 31; break; }}}

Page 8: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 88

#include <iostream>

using namespace std;

void main()

{

char letter;

bool gotAVowel = false;

do

{

cout << "Please enter a letter: ";

cin >> letter;

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";

}

}while(!gotAVowel);

}

The break statements ensure

that the switch statement is exited

once the appropriate case is handled.

Without the break statements, all cases

might execute.

The default case is executed if no other case

value matches.

Page 9: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 99

Conditional StatementsConditional StatementsC++ conditional statements provide a concise C++ conditional statements provide a concise alternative to the use of relatively simplealternative to the use of relatively simple if-else if-else statements.statements.

if (year % 4 == 0)if (year % 4 == 0) daysInMonth = 29;daysInMonth = 29;elseelse daysInMonth = 28;daysInMonth = 28;

daysInMonth = (year % 4 == 0) ? 29 : 28;daysInMonth = (year % 4 == 0) ? 29 : 28;

if (val > 0)if (val > 0) cout << “GOOD”;cout << “GOOD”;elseelse cout << “BAD”;cout << “BAD”;

(val > 0) ? (cout << “GOOD”) : (cout << “BAD”);(val > 0) ? (cout << “GOOD”) : (cout << “BAD”);

Page 10: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 1010

TheThe for for StatementStatementThe C++The C++ for for statement is designed to facilitate looping statement is designed to facilitate looping when the control of the loop contains three standard when the control of the loop contains three standard features:features:

• An initialization action that is performed just before the An initialization action that is performed just before the loop is started the first time.loop is started the first time.

• A Boolean expression that is checked just before A Boolean expression that is checked just before entering the loop at each iteration.entering the loop at each iteration.

• An update action that is performed just after each An update action that is performed just after each iteration of the loop is completed.iteration of the loop is completed.

for (for (initActioninitAction; ; booleanExpbooleanExp; ; updateActionupdateAction)) bodyOfLoopbodyOfLoop

Page 11: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 1111

#include <iostream>using namespace std;

const double PAY_RATE = 10.15;

void main(){ double payForWeek = 0.0; int dayOfWeek; double hoursWorked;

for(dayOfWeek = 1; dayOfWeek <= 7; dayOfWeek++) { cout << "How many hours did you work on day " << dayOfWeek << "? "; cin >> hoursWorked; (dayOfWeek == 1) ? (payForWeek += 1.5 * hoursWorked * PAY_RATE) : (payForWeek += hoursWorked * PAY_RATE); }

cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2);

cout << endl << endl << "Your Pay For \n" << "The Week Is $" << payForWeek << endl << endl;}

dayOfWeek is initialized to 1when the for-loop is first

encountered.

This inequality is checked just before the

body of the loop is entered (or re-entered).This increment

statement is executed right

after each execution of the body of the loop.

AA for for-loop Example-loop Example

Page 12: Chapter 3 More Flow of Control Goals: To analyze the use of Boolean expressions To analyze the use of Boolean expressions To introduce the notion of enumerated

Chapter 3Chapter 3CS 140CS 140 Page Page 1212

#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;}

NestedNested for for-loops-loops