Section 5.1 Worked Example: If Statements
Subgoals for Evaluating Selection Statements.
- Diagram which statements go together
- For if statement, determine whether expression is true or false
- If true – follow true branch, if false – follow else branch or do nothing if no else branch
Subsection 5.1.1
You can watch this video or read through the content below it.
Given the following declarations:
double omega = 2.5;
double kappa = 3.0;
double rho = 0.0;
Evaluate these statements and determine the value of all variables used.
if (kappa > omega)
rho = kappa + 2;
Subsection 5.1.2 SG1: Diagram which statements go together.
If no { } are present, then by default all if and else branches have only a single statement:
if (kappa > omega)
rho = kappa + 2;
Subsection 5.1.3 SG2: For if statement, determine whether true or false
First we evaluate (kappa > omega):
(3.0 > 2.5)
is TRUESubsection 5.1.4 SG3: If true, follow true branch. If false, follow else branch (OR do nothing if there is no else branch).
The condition is TRUE so we execute the true branch:
rho = kappa + 2
= 3.0 + 2
= 5.0
Answer.
omega
= 2.5, kappa
= 3.0, rho
= 5.0;Practice Pages.
You have attempted of activities on this page.