CS 140 Introduction to Computing I

Download Report

Transcript CS 140 Introduction to Computing I

Chapter 3
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 for-statement 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.
• Order-related 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 left-to-right fashion.
CS 140
Chapter 3
Page 2
Precedence Rules Examples
int x = 7,
if (x == y
cout <<
else
cout <<
y = 7, z = 7;
== z)
“YES”;
“NO”;
Output: NO
The left equality is checked and
evaluates to true (numerical 1),
which is not equal to the z-value!
CS 140
Chapter 3
int a =
if (a <
cout
else
cout
5, b = 4, c = 3;
b < c)
<< “YES”;
<< “NO”;
Output: YES
The left inequality is checked and
evaluates to false (numerical 0),
which is less than the c-value!
Page 3
Boolean Expressions Short-Circuit 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 != 0) && (y/x > 1))
z = 100;
else
z = -1;
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
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 3
Page 4
Boolean Expressions Short-Circuit 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 3
Page 5
Enumerated
Types
To enhance the readability of one’s code, a
programmer can define an enumerated type,
which consists of a set of integer 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;
}
CS 140
Chapter 3
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 3
Page 7
#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 no
}while(!gotAVowel);
}
other case value matches.
CS 140
Chapter 3
Page 8
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”;
if (year % 4 == 0)
daysInMonth = 29;
else
daysInMonth = 28;
CS 140
(val > 0) ? (cout << “GOOD”) : (cout << “BAD”);
daysInMonth = (year % 4 == 0) ? 29 : 28;
Chapter 3
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 3
Page 10
A for-loop Example
#include <iostream>
using namespace std;
const double PAY_RATE = 10.15;
void main()
dayOfWeek is initialized to
{
1when the for-loop is first
double payForWeek = 0.0;
encountered.
int dayOfWeek;
double hoursWorked;
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.
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;
}
CS 140
Chapter 3
Page 11
Nested for-loops
#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 3
Page 12