Title: CS 240 Section 3
1CS 240 Section 3
Keep Cool Under Pressure
- Computer Science I
- Dr. Dale E. Nelson
2Chapter 4 Basic Flow of Control(Conditional
decisions and Iteration)
3Chapter Goals
- To be able to implement decisions using if
statements - To understand statement blocks
- To learn how to compare integers, floating-point
numbers, and strings - To develop strategies for processing input and
handling errors - To understand the Boolean data type
- To avoid infinite loops and off-by-one errors
4The if Statement
- The if statement is used to implement a decision.
- It has two parts a test and a body.
- Example
- if (area lt 0)
- cout ltlt "Error Negative area.\n"
- Multiple statements can be grouped together in a
block statement by enclosing them in braces - if (area lt 0)
-
- cout ltlt "Error Negative area.\n"
- return 1
-
5The if Statement (Syntax 4.1 if Statement)
Syntax 4.1 if Statement if (condition)
statement Example if (x gt 0) y
sqrt(x) Purpose Execute the statement if the
condition is true.
6The if Statement (Syntax 4.2 Block Statement)
Syntax 4.2 Block Statement statement1
statement2 ... statementn Example
double length sqrt(area) cout ltlt area ltlt
"\n" Purpose Group several statements into a
block that can be controlled by another statement.
7The if Statement (area1.cpp)
include ltiostreamgt include ltstringgt
include ltcmathgt using namespace std int
main() //Variables double
area //area of square in square inches
double length //length of side of square in
inches cout ltlt "Please enter the area of
a square " cin gtgt area if
(area lt 0) cout ltlt
"Error Negative area.\n" return
1 / now we know that area
is gt 0 / length sqrt(area)
cout ltlt "The side length of the square is "
ltlt length ltlt "\n" return 0
8The if/else Statement
- The if/else consists of a condition of two
alternatives. - The first condition is performed is the condition
is true. - The second condition is performed if the
condition is false. - if (area gt 0)
- cout ltlt "The side length is " ltlt
sqrt(area) ltlt "\n" - else
- cout ltlt "Error Negative
area.\n" - The if/else statement is a better choice than a
pair of if statements with complementary
conditions. - if (area gt 0) / complementary conditions
/ - cout ltlt "The side length is " ltlt
sqrt(area) ltlt "\n" - if (area lt 0) / complementary conditions /
- cout ltlt "Error Negative area.\n"
9The if/else Statement(Syntax 4.3 if/else
Statement)
Syntax 4.3 if Statement if (condition)
statement1 else statement2 Example if (x gt 0)
y sqrt(x) else cout ltlt "Bad
input\n" Purpose Execute the first statement if
the condition is true, the second statement if
the condition is false.
10The if/else Statement(Syntax 4.3 if/else
Statement)
include ltiostreamgt include ltstringgt
include ltcmathgt using namespace std int
main() //Variables double area
//Area of a square in square inches cout ltlt
"Please enter the area of a square " cin
gtgt area if (area gt 0) cout ltlt
"The side length is " ltlt sqrt(area) ltlt "\n"
else cout ltlt "Error Negative area.\n"
return 0
11Relational Operators
12Relational Operators
- C has six relational operators to implement
conditions
13Operator Precedence
- Highest
- ( )
- ! -- -
- /
- -
- lt lt gt gt
- !
-
-
- - /
- Lowest
14Relational Operators (comparing strings)
- The relational operators listed above can also be
used to compare strings using lexicological
comparison. - "car" is less than "cargo"
-
- "cargo" is less than "cathode"
-
15Input Validation
- Input validation is an application of the if
statement that verifies the user has given
reasonable input. - Example
- double area
- cin gtgt area
- user types "five" and hits return! (Causing cin
to fail). - After every input a good program will test
- if (cin.fail())
- The actual input should also be validated, even
if the type is correct. - if (area lt 0)
- Other strategies
- if (cin)
- / the stream did not fail /
- else
- / the stream failed /
- if (cin gtgt x) ...
16Input Validation (area3.cpp)
include ltiostreamgt include ltstringgt
include ltcmathgt using namespace std int
main() //Variables double area
//Area of a square in square inches cout ltlt
"Please enter the area of a square " cin
gtgt area //Check for valid input if
(cin.fail()) cout ltlt "Error Bad
input\n" return 1 if
(area lt 0) cout ltlt "Error
Negative area.\n" return 1
cout ltlt "The side length is " ltlt sqrt(area) ltlt
"\n" return 0
17Simple Loops
- A loop is a block of code that can be performed
repeatedly. - A loop is controlled by a condition that is
checked each time through the loop. - The while statement makes a check before each
execution of the code. - / how long does it take an investment to double?
/ - while( balance lt 2 initial_balance)
-
- balance balance ( 1 rate / 100)
- year
-
18Simple Loops (Syntax 4.4 while Statement)
Syntax 4.4 while Statement while (condition)
statement Example while (x gt 10) x
sqrt(x) Purpose Execute the statement while the
condition remains true.
19Processing a Sequence of Inputs (Sentinels)
- Whenever you read a sequence of input values, you
need to have some method of terminating the
input. - A number used to signal termination is called a
sentinel. - Sentinels only work if there is some restriction
on the input. - Common sentinel values are 0 or -1.
20Processing a Sequence of Inputs (sentinel.cpp)
include ltiostreamgt using namespace std
int main() //Variables double sum
0 //Total of all salaries in dollars int
count 0 //Number of salaries read
double salary 0 //Employee salary in dollars
while (salary ! -1) cout ltlt
"Enter a salary, -1 to finish " cin gtgt
salary if (salary ! -1)
sum sum salary count
if (count gt 0) cout ltlt
"Average salary " ltlt sum / count ltlt "\n"
return 0
21Processing a Sequence of Inputs (Causing the
Stream to Fail)
- When reading input from the console, you can
close the stream manually. - Ctrl Z in Windows
- Ctrl D in UNIX
- Reading from a closed stream causes the stream to
enter the failed state.
22Processing a Sequence of Inputs (maxtemp.cpp)
include ltiostreamgt using namespace std
int main() //Variables double next
//Temperature in degrees F double
highest //Highest temperature in degree F
cout ltlt "Please enter the temperature
values\n" if (cin gtgt next) highest
next else cout ltlt "No
data!\n" return 1 while
(cin gtgt next) if (next gt highest)
highest next cout ltlt
"The highest temperature is " ltlt highest ltlt
"\n" return 0
23Using Boolean Variables
- The bool type can hold exactly two values,
denoted false and true. - Boolean variables are named after George Boole
(1815-1864), a pioneer in the study of logic. - Example
- bool more true
- while (more)
-
- cin gtgt next
- if (cin.fail())
- more false
- else
-
- // process next
-
-
- Don't
- while(more false) / don't /
- while(more ! false) / don't /
24Case Study
- Crazy Als Computer Emporium Case Study
- Crazy Als Computer Emporium is a retail seller
of home computers. The sales staff at Crazy Als - work strictly on commission. At the end of the
month, each salespersons commission is
calculated - according to Table 4A.
- For example, a salesperson with 16,000 in
monthly sales will earn a 12 commission
(1,920.00). - Another salesperson with 20,000 in monthly sales
will earn a 14 commission (2,800.00). - Because the staff only gets paid once per month,
Crazy Als allows each employee to take up - to 1,500 per month in advance. When sales
commissions are calculated, the amount of each - employees advanced pay is subtracted from the
commission. If any salespersons commissions are - less than the amount of their advance, they must
reimburse Crazy Als for the difference. - Here are two examples Beverly and John have
21,400 and 12,600 in sales, respectively. - Beverlys commission is 2,996 and Johns
commission is 1,260. Both Beverly and John took - 1,500 in advance pay. At the end of the month,
Beverly gets a check for 1,496, but John must - pay 240 back to Crazy Als.
- Youve been asked to write a program that eases
the task of calculating the end-of-month
25Program Design
- Select variable required by the program
- Create general pseudocode
- Create detailed pseudocode
- Expand to final program
- First comments, includes, namespace
- Second begin program and define variables
- Third get input
- Fourth determine commission rate
- Fifth calculate commission and remaining pay
- Sixth display results and return
26Case Study