Decisions: October 4, 2017
Decisions: October 4, 2017
October 4, 2017
0 of 17
The if Statement
Syntax
if(condition)
statement 1;
Syntax
if(condition)
{
statement 1;
statement 2;
...
statement n;
}
1 of 17
if - Example
Example 1
Run the following example Ch03 E1.cpp
Try different inputs (e.g. 130, 85, 120)
2 of 17
The if/else Statement
Syntax
if(condition)
statement 1;
else
statement 2;
3 of 17
if/else - Example
Example 2
Run the following example Ch03 E2.cpp
Try different inputs (e.g. 130, 85, 120)
4 of 17
Comparison - if vs. if/else
Question
Do you observe any difference in the output of Example 1 and
Example 2?
5 of 17
Relational Operators
6 of 17
Boolean Operators
7 of 17
Example
Example 3
Write a program that reads in car type and car speed from the
user and display on the screen whether the car is exceeding
speed limit or car is under the speed limit. There are two
categories for car type: LTV and HTV. The speed limit for
LTV and HTV is 120 and 110 respectively.
Code
See example Ch03 E3.cpp and go through the code.
8 of 17
Flowcharts
Condition
if Statement
if(Condition) TRUE
FALSE
Statement 1;
Statement 2; Statement 1
Statement 2
9 of 17
Flowcharts
Condition
if-else Statement
if(Condition) FALSE
TRUE
Statement 1;
else Statement 1 Statement 2
Statement 2;
Statement 3;
Statement 3
10 of 17
Flowcharts
11 of 17
Flowcharts
switch Statement
switch (Condition)
{
Case 1:
Statement 1;
Draw flowchart for switch
break;
statement.
Case 2:
Statement 2;
break;
default:
Statement 3;
break;
}
12 of 17
Programming Exercise
Sample output
Please enter three numbers: 11 3.7 2
The largest number is 11
Code
See Ch03 E4.cpp
13 of 17
Programming Exercise
Sample output
Please enter three numbers: 11 3.7 2
The smallest number is 2
Code
See Ch03 E5.cpp
14 of 17
Programming Exercise
Sample output
Please enter three strings: Chemistry Biology Physics
Biology
Chemistry
Physics
Code
See Ch03 E6.cpp
15 of 17
Programming Exercise
Example 7 - Integer to number of digits
Write a program that reads an integer and prints how many
digits the number has, by checking whether the number is 10,
100, and so on.
(Assume that all integers are less than one million.)
If the number is negative, first multiply it with –1.
Sample output
Enter an integer: 100
Digits = 3
Code
See Ch03 E7.cpp
16 of 17
Programming Exercise
Sample output
Enter a month: 3
31 Days
Code
See Ch03 E8.cpp
17 of 17
Common Errors - The if statement
A semicolon after the if statement
if (a == 1) ; // Error
{
cout<<"one";
}
19 of 17