Chapter 4: Basic Control Flow
Chapter Goals
- To be able to implement decisions and loops
using if
and while statements
- To understand statement blocks
- To learn how to compare integers,
floating-point
numbers,
and strings
- To develop strategies for processing input and
handling input
errors
- To understand the Boolean data type
The if Statement
Syntax
4.1: if
Statement
if (condition) statement
Example: |
if (x >= 0) y = sqrt(x);
|
Purpose: |
Execute the statement if the condition
is true. |
|
Syntax
4.2:
Block Statement
{ statement1 statement2 ... statement }
Example: |
{ double length = sqrt(area); cout << area << "\n"; }
|
Purpose: |
Group several statements into a block
that can be controlled
by another statement. |
|
The if Statement (area1.cpp)
The if/else Statement
- The if/else consists of a condition
of
two alternatives.
- The first alternative is performed if the
condition
is true.
- The second alternative is performed if the
condition is false.
if (area >= 0)
cout << "The side length is " << sqrt(area) << "\n";
else
cout << "Error: Negative area.\n";
- [Flowchart]
- The if/else statement is a better
choice
than a
pair of if statements with complementary conditions.
if (area >= 0) /* complementary conditions */
cout << "The side length is " << sqrt(area) << "\n";
if (area < 0) /* complementary conditions */
cout << "Error: Negative area.\n";
Syntax
4.3: if
Statement
if (condition) statement1 else statement2
Example: |
if (x >= 0) y = sqrt(x); else cout << "Bad input\n";
|
Purpose: |
Execute the first statement if the
condition is true,
the second statement if the condition is false. |
|
The if/else Statement (area2.cpp)
The selection operator
C++ has a selection operator of the form:
test ? value1 : value2
The value of this expression is either value1 if the test passes or value2 if it fails.
y = x >= 0 ? x : -x;
is equivalent to
if (x >= 0) y = x;
else y = -x;
Expression
|
Statement
|
x >= 0 ? x : -x
|
if (x >= 0) y = x; else y = -x;
|
y = x
|
y = x;
|
-b + sqrt(d)
|
-b + sqrt(d);
|
Relational Operators
- C++ has six relational
operators to implement
conditions:
C++
|
Description
|
Example
|
Notes
|
>
|
greater than
|
a > 5
|
|
>=
|
greater than or equal to
|
x >= 5
|
Be careful to not write =>
Remember that the symbols appear in the order
you say
them
|
<
|
less than
|
x < 10
|
|
<=
|
less than or equal to
|
x <= 11
|
Be careful to not write =<
Remember that the symbols appear in the order
you say
them
|
==
|
equal to
|
a == 5
|
Don't
confuse with =
which is assignment
|
!=
|
not equal
|
a != 5
|
The ! is supposed to be the line that
"crosses through"
the equal sign |
Relational Operators (comparing strings)
- The relational operators listed above can also
be
used to
compare strings using lexicographic comparison.
- When comparing strings, corresponding letters are
compared until one of the strings ends or the first difference is
encountered.
- "car" is less than "truck",
i.e. the condition "car" < "truck" is true.
- "car" is less than "cargo",
i.e. the condition "car" < "cargo" is true.
-
"cargo" is less than "cathode",
i.e. the condition "cargo" >= "cathode" is false.
ASCII Table
(American Standard Code for Information Interchange)
0-31 are control codes, for example /n
(newline) has an ASCII code 10.
32: 33:!
34:" 35:# 36:$
37:% 38:& 39:' 40:( 41:)
42:* 43:+ 44:, 45:- 46:.
47:/ 48:0 49:1 50:2 51:3
52:4 53:5 54:6 55:7 56:8
57:9 58:: 59:; 60:< 61:=
62:> 63:? 64:@ 65:A 66:B
67:C 68:D 69:E 70:F 71:G
72:H 73:I 74:J 75:K 76:L
77:M 78:N 79:O 80:P 81:Q
82:R 83:S 84:T 85:U 86:V
87:W 88:X 89:Y 90:Z 91:[
92:\ 93:] 94:^ 95:_ 96:`
97:a 98:b 99:c 100:d 101:e
102:f 103:g 104:h 105:i 106:j 107:k 108:l 109:m 110:n
111:o
112:p 113:q 114:r 115:s 116:t 117:u 118:v 119:w 120:x
121:y
122:z 123:{ 124:| 125:} 126:~ 127: 128:Ђ 129:Ѓ 130:‚
131:ѓ
132:„ 133:… 134:† 135:‡ 136:€ 137:‰ 138:Љ 139:‹ 140:Њ
141:Ќ
142:Ћ 143:Џ 144:ђ 145:‘ 146:’ 147:“ 148:” 149:• 150:–
151:—
152:� 153:™ 154:љ 155:› 156:њ 157:ќ 158:ћ 159:џ 160:
161:Ў
162:ў 163:Ј 164:¤ 165:Ґ 166:¦ 167:§ 168:Ё 169:© 170:Є
171:«
172:¬ 173: 174:® 175:Ї 176:° 177:± 178:І 179:і 180:ґ
181:µ
182:¶ 183:· 184:ё 185:№ 186:є 187:» 188:ј 189:Ѕ 190:ѕ
191:ї
192:А 193:Б 194:В 195:Г 196:Д 197:Е 198:Ж 199:З 200:И
201:Й
202:К 203:Л 204:М 205:Н 206:О 207:П 208:Р 209:С 210:Т
211:У
212:Ф 213:Х 214:Ц 215:Ч 216:Ш 217:Щ 218:Ъ 219:Ы 220:Ь
221:Э
222:Ю 223:Я 224:а 225:б 226:в 227:г 228:д 229:е 230:ж
231:з
232:и 233:й 234:к 235:л 236:м 237:н 238:о 239:п 240:р
241:с
242:т 243:у 244:ф 245:х 246:ц 247:ч 248:ш 249:щ 250:ъ
251:ы
252:ь 253:э 254:ю 255:
This is Windows-1251 encoding table.
Input Validation
- Input validation is an application of the if
statement that
verifies the user has given reasonable input.
- Example:
double area;
cin >> area;
The user types "five" and hits return!
Causing cin
to fail, variable area is
not set.
-
After every input a good
program will
test (invoking fail()
member-function of ifstream
class):
if (cin.fail())
- The actual input should also be validated, even
if the type is correct.
if (area < 0)
- Other strategies
-
A stream variable can be the condition of an if statement:
if (cin)
/* the stream did not fail */
else
/* the stream failed */
-
The expression cin
>> x has a value, namely cin.
It follows that we can chain the >>
operators:
cin >> x >> y /* which means (cin >> x) >> y */
We can use the stream expression as the
condition of an if
operator:
if (cin >> x) ...
means "read x,
and if that didn't make cin
fail, then
continue".
Input Validation (area3.cpp)
Simple Loops
- Recall the investment problem from Chapter 1.
You put $10,000 into a
bank account that earns 5% interest per year. How many years does it
take for the account balance to be double the original? |
-
Step 1: Start with
the table
(int
year = 0; double balance = 10000;)
After Year
|
Balance
|
0
|
$10,000
|
-
Step 2: Repeat steps 2a-2c while balance
< $20,000
(balance < 20000)
-
Step 2a. Add a new row to the table
-
Step 2b. In column 1 of the new row,
put one more than the preceding year's value
(year++;)
-
Step 2c. In
column 2, place the value of the preceding balance value, multiplied by
1.05
(balance
= balance*1.05;)
- Step 3: Report the last number in the year
column as the number of years required to double the investment
Syntax
4.4: while
Statement
while (condition) statement
Example: |
while (x >= 10) x = sqrt(x);
|
Purpose: |
Execute the statement while the
condition remains true. |
|
Processing 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.
Processing a Sequence of Inputs (sentinel.cpp)
Processing a Sequence of Inputs (Causing the Stream to Fail)
- When reading input from the console, you can
close
the input stream
manually.
- Ctrl + Z in Windows
- Ctrl + D in UNIX
- Reading from a closed stream causes the stream
to
enter the
failed state.
Processing a Sequence of Inputs (maxtemp.cpp)
Using Boolean Variables