Conditional (Branching) Statements
Chapter 4
Control Structures
A computer can proceed:
- In sequence
- Selectively (branch): making a choice
- Repetitively (iteratively): looping
- By calling a function
Here are subsections of flowcharts showing the first three:
So far, our program instructions have only proceeded in sequence. We will not add selectivity.
Let’s look inside the decisions (“diamonds”) – this is where we need to make a decision about what we are going to do next. For instance, if we are assigning grades, if the grade is between 90 and 100 it is an A, if 80-90 it’s a B, etc. So we decide what to do based on our input.
- Conditional statements: only executed if certain conditions are met
- Condition: represented by a logical (Boolean) expression that evaluates to a logical (Boolean) value of true or false
There are two structures for these conditional statements:
- if…then…else statements
- switch statements
If…then…else Statement
if (guard statement)
{
// If true, then do whatever is in these {}
}
else
{
// If false, do this instead
}Examples
Just if statement:
cppif (grade > 90) { letter = 'A'; }If…then…else:
cppif (grade > 70) { letter = 'P'; // P for pass } else { letter = 'F'; // F for fail }Block of if…then…else statements (nested if/else):
cppif (grade >= 90) { letter = 'A'; } else if (grade >= 80) { letter = 'B'; } else if (grade >= 70) { letter = 'C'; } else if (grade >= 60) { letter = 'D'; } else { letter = 'F'; }
Expression of char values with relational operators:
- The result depends on the machine’s collating sequence.
- ASCII character set
Nesting
Nesting: one control statement is located within another.
An else is associated with the most recent if that has not been paired with an else.
if (month == 2) // Determine how many days are in February this year.
{
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
days = 29; // leap year
else
days = 28; // normal year
}Logical Expressions
Logical (Boolean) expressions:
- Expressions such as
4 < 6and'R' > 'T' - Returns an integer value of
1if the logical expression evaluates totrue - Returns an integer value of
0otherwise
The bool Data Type
- The data type
boolhas logical (Boolean) values true and false bool,true, andfalseare reserved words- The identifier
truehas the integer value1(or not0) andfalsehas the value0.
Relational (Boolean) Operators
| Operator | Description | Syntax |
|---|---|---|
== | equal to | num1 == num2 |
!= | not equal to | num1 != num2 |
< | less than | num1 < num2 |
<= | less than or equal to | num1 <= num2 |
> | greater than | num1 > num2 |
>= | greater than or equal to | num1 >= num2 |
String Comparisons
Relational operators can be applied to strings.
- Strings are compared character by character, starting with the first character.
- The comparison continues until either a mismatch is found or all characters are found equal.
- If two strings of different lengths are compared and the comparison is equal to the last character of the shorter string
- The shorter string is less than the larger string
Multiple Comparisons
You can combine multiple comparisons into a single expression with logical (Boolean) operators.
Unlike relational operators (which compare values), logical operators take Boolean expressions and produce a Boolean result.
This video covers how to perform multiple comparisons using the logical operators AND (&&) and OR (||). We also cover the NOT (!) operator.
| Operator | Description | Syntax |
|---|---|---|
! | not | !val |
&& | and | val1 && val2 |
|| | or | val1 || val2 |
Things to look out for:
A “dangling”
else(You cannot have an else without a matching if directly preceding it.)Else statements cannot have conditionals; only if statements.
cppelse (num > 3) // this is an error; you need: else if (num > 3)Using a
=when you mean==- The appearance of
=in place of==resembles a silent killer (no syntax error, but a semantic error).
- The appearance of
Forgetting to break in a switch statement.
Everything is a number (even Booleans and characters)
Any value that is not
0is evaluated astruewhen interpreted as a Boolean.Don’t forget to use
&&and||when doing multiple comparisonscpp0 < num1 < 10 // Error: is true for any number greater than 0!` (0 < num1) < 10 // Here is the order of operations. See the problem? 0 < num1 && num1 < 10 // Correct: true for num1 values between 1 and 10
A dangling else means that you have an else that is going with the wrong if statement.
Self-Check Questions
- What is a conditional?
- What is the difference between a
=and==? - Be able to create an if…else; if…else…if…else; and switch statements.