Scripting and Programming C173: Unit 3 – Branches

17 pages

3.1 Branches

Branches

In a program, a branch is a sequence of statements only executed under a certain condition. In Coral flowcharts, a decision creates two branches: If the decision’s expression is true, the first branch executes, else the second branch executes. Afterwards, the branches rejoin. Coral flowcharts use a diamond symbol for a decision.

  1. A decision leads to two program branches. If the expression is true, the first branch executes. Else, the second branch executes.
  2. If userAge is 68, then 68 > 65 is true so the first branch executes, which discounts hotelRate.
  3. Execution rejoins the other branch, and continues with subsequent statements, outputting 135. If userAge were instead 50, the output would be 155.

A decision and its two branches are often called if-else branches, because IF the decision’s expression is true then the first branch executes, ELSE the second branch executes.

In the example above, the else (false) branch had no statements. A decision whose false branch has no statements is often just called an if branch.

If-elseif branches

A branch may itself contain a decision and branches. Commonly, a series of decisions appear cascaded in each decision’s false branch, known as if-elseif branches, to detect specific values of a variable. The example below detects values of 1, 25, or 50 for variable numYears. if-elseif branches are typically drawn with the decision boxes stacked vertically.

The example below uses ==. The equality operator == evaluates to true if the left and right sides are equal. Ex: If numYears is 10, then numYears == 10 evaluates to true. Note the equality operator is ==, not =.

  1. This cascaded decision structure is common to detect a specific value of a variable. If numYears is 1, the first branch executes.
  2. Else, if numYears is 25, the second branch executes. Else, if numYears is 50, the third branch executes.
  3. Else, the last branch executes.

3.2 More branches

Nested if-else branches

If-else branches have two branches. A branch’s statements can include any valid statements, including another if-else branch, known as nested branches. The nested branches can take on various forms, and the if-else branches may even use different variables.

3.3 Equality and relational operators

Equality operators

An equality operator checks whether two operands’ values are the same (==) or different (!=). Note that equality is ==, not just =.

An expression involving an equality operator evaluates to a Boolean value. A Boolean is a type that has just two values: true or false.Table 3.3.1: Equality operators.

Equality operatorsDescriptionExample (assume x is 3)
==== b means a is equal to bx == 3 is true
x == 4 is false
!=!= b means a is not equal to bx != 3 is false
x != 4 is true

Relational operators

relational operator checks how one operand’s value relates to another, like being greater than.

Some operators like >= involve two characters. A programmer cannot arbitrarily combine the >, =, and < symbols; only the shown two-character sequences represent valid operators in Coral (and most languages).Table 3.3.2: Relational operators.

Relational operatorsDescriptionExample (assume x is 3)
<< b means a is less-than bx < 4 is true
x < 3 is false
>> b means a is greater-than bx > 2 is true
x > 3 is false
<=<= b means a is less-than-or-equal to bx <= 4 is true
x <= 3 is true
x <= 2 is false
>=>= b means a is greater-than-or-equal to bx >= 2 is true
x >= 3 is true
x >= 4 is false

Example: Golf scores

In golf and miniature golf, each hole has a “par” indicating the normal number of strokes to get the ball in the hole. The following program outputs special names for numbers below par. The program uses one relational operator, and several equality operators, in a multi-branch if-else statement.

3.4 Detecting ranges using branches

Decision sequences and ranges

People regularly deduce ranges based on a decision sequence. Ex: In a soccer league, no teams may exist for players 5 and under. So, a “U8” division (“Under 8”) is deduced to be for ages 6-7, and not for 1-7 because players 5 and under are already excluded. Likewise, U10 would be 8-9 because 6-7 is already covered by U8.

  1. Kids of various ages may wish to play soccer. A soccer club may not have teams for kids 5 and under.
  2. One level of teams is listed as “Under 8” (orU8), which is understood to mean just for ages 7 and 6, but not 5 and younger.
  3. Likewise, U10 means ages 9 and 8, and U12 means 11 and 10. No teams exist for ages 12 and over.
  4. Using a sequence of decisions enables a concise way of specifying a range, such as saying U12 rather than saying ages 10 and 11.

3.5 Logical operators

Logical and, or, not

logical operator treats operands as being true or false, and evaluates to true or false. Logical operators include and, or, not.

  1. The and operator evaluates to true only if BOTH operands are true. Each operand (a, b above) is an expression that evaluates to true or false.
  2. The or operator evaluates to true if ANY operand is true (a, b, or both).
  3. The not operator evaluates to the opposite of the operand.
  4. Each operand is an expression. If x = 7, y = 9, then (x > 0) and (y < 10) is true and true, so the and operator evaluates to true (both operands are true).

Table 3.5.1: Logical operators.

Logical operatorDescription
(a) and (b)Logical and: true when both operands are true
(a) or (b)Logical or: true when at least one of the two operands is true
not(a)Logical not: true when the one operand is false, and vice-versa
  1. In mathematics, the range 10 < x < 15 means that x may be 11, 12, 13, 14.
  2. In a program, such a range is specified using two < operators along with the and operator. 10 < x defines the range above 10.
  3. x < 15 defines the range below 15. Adding the and operator yields the overlapping range. Only when x is 11, 12, 13, or 14 will both expressions be true.
  1. A common cascaded arrangement of decisions detects ranges of a variable. The first true branch executes for values < 0, the second for 0-9, and the third for 10-19.
  2. If the first decision’s userNum < 0 yielded false, userNum must be >= 0, so the next decision need not check for >= 0, and can just check for userNum < 10.
  3. Likewise for the next decision: userNum must be >= 10, so only < 20 is checked. Such implicit ranges have easier-to-read expressions.

Detecting ranges implicitly vs. explicitly

If a program should detect increasing ranges without gaps, cascaded decisions can be used without logical operators; the low-end of the range is implicitly known upon reaching an expression. Likewise, a decreasing range without gaps has implicitly-known high-ends. In contrast, when gaps exist, the range’s low and high ends must both be explicitly detected, using a logical operator.

3.6 Order of evaluation

Precedence rules

The order in which operators are evaluated in an expression are known as precedence rules. Arithmetic, logical, and relational operators are evaluated in the order shown below.Table 3.6.1: Precedence rules for arithmetic, logical, and relational operators.

Operator/ConventionDescriptionExplanation
( )Items within parentheses are evaluated firstIn (a * (b + c)) - d, the + is evaluated first, then *, then -.
notLogical not is nextnot(x == 1) or y is evaluated as (not(x == 1)) or y
* / % + –Arithmetic operators (using their precedence rules; see earlier section)z - 45 * y < 53 evaluates * first, then -, then <.
<   <=   >   >=Relational operatorsx < 2 or x >= 10 is evaluated as (x < 2) or (x >= 10) because < and >= have precedence over the or operator.
==   !=Equality and inequality operatorsx == 0 and x >= 10 is evaluated as (x == 0) and (x >= 10) because == and >= have precedence over the and operator.
andLogical andx == 5 or y == 10 and z != 10 is evaluated as (x == 5) or ((y == 10) and (z != 10)) because the and operator has precedence over the or operator.
orLogical ORor has the lowest precedence of the listed arithmetic, logical, and relational operators.
  1. Expressions like x + 1 > y * z or z == 3 are evaluated using precedence rules. Among +, >, *, or, ==, the * comes first.
  2. Next comes +, then ==, and finally or.
  3. The expression is actually treated like a “tree”, evaluated from the bottom upwards.
  4. If x is 7, y is 6, and z is 3, then y * z is 18. Next, x + 1 is 8. Next, 8 > 18 is false. Next, z == 3 is true. Finally, false or true is true.

3.7 Example: Toll calculation

Calculating toll based on time of day

This section presents an example program that calculates the toll amount for travel along a toll road or toll lane. The toll amount is based on the time of day, day of the week, and number of persons in the vehicle.

The initial version of the program calculates the toll amount for travel on a weekday based upon the toll schedule below. The table lists times in both am/pm format and 24-hour format.Table 3.7.1: Weekday toll schedule.

Time (am/pm)Time (24 hour)Toll amount
Before 6:00 amBefore 6:001.50
6:00 am to 9:59 am6:00 to 9:594.60
10:00 am to 5:59 pm10:00 to 17:592.30
6:00 pm and after18:00 and after1.50

Feedback?

The program gets the time of travel from the user using 24 hours format, and uses the hour to determine the toll amount. If-elseif branches determine in which range the hour belongs and assign tollAmount with the toll based on the table above. Then the toll amount is output.

3.8 Floating-point comparison

Floating-point numbers should not be compared using the == operator. Ex: Avoid float1 == float2. Reason: Some floating-point numbers cannot be exactly represented in the limited available memory bits like 64 bits. Floating-point numbers expected to be equal may be close but not exactly equal.

  1. Floating-point numbers can’t always be exactly represented in limited memory bits. 0.7 is actually 0.6999… 0.4 is 0.400…00222… 0.3 is 0.2999… Thus, 0.7 – 0.4 – 0.3 should be 0 but is actually -0.00…0055…
  2. Thus, floats should not be compared with ==. If numMeters = 0.7, and then 0.4 is subtracted, then 0.3 is subtracted, then numMeters == 0.0 should yield true but will actually yield false.
  3. Instead, floats should be compared for “close enough”: If the difference is less than say 0.0001, the values are considered equal. Absolute value is applied since the difference could be negative.

Floating-point numbers should be compared for “close enough” rather than exact equality. Ex: If (x – y) < 0.0001, x and y may be deemed equal. Because the difference may be negative, the absolute value is used: AbsoluteValue(x – y) < 0.0001. AbsoluteValue() is a math function built into Coral. The difference threshold indicating that floating-point numbers are equal is often called the epsilon. Epsilon’s value depends on the program’s expected values, but 0.0001 is common.

Example: Body temperature

The example below shows how floating-point values should be compared in a program, comparing for close enough, rather than using the == operator.

Observing inexact representation of floating-point values

The tool below allows a user to type a value and see how that value is actually represented in a 32-bit floating-point representation. The user can ignore the 0’s and 1’s, and just notice the actual represented value. One might type 0.7 and notice the represented value is 0.6999… Other numbers like 0.25 can be represented exactly.

3.9 Code: Branches

If statements and if-else statements

In code, an if-else branch is written as an if-else statement: An if decision expression with the true branch’s sub-statements, followed by an else part with any false branch sub-statements. An if statement is an if decision expression followed by sub-statements, with no else part.

  1. In code, a decision uses the word “if” followed by the expression.
  2. The true branch’s sub-statements start on the next line and are indented.
  3. If the expression is true, the true branch executes. If the expression is false, execution just proceeds to the subsequent statements.
  4. For a program having statements in the else (false) branch, the code’s if-else statement has an else part, with indented sub-statements as well.

integer val

val = Get next input

if val < 0
val = -val

Put val to output

If-else statement example: Insurance prices

In the example below, if a user inputs an age less than 25, the statement insurePrice = 4800 executes. Else, insurePrice = 2200 executes.

  1. In an if-elseif statement, the first expression that evaluates to true has its branch execute.
  2. Execution then jumps to after the if-elseif statement.


integer numYears

numYears = Get next input

if numYears == 1

Put “Newlyweds” to output

elseif numYears == 25

Put “Silver” to output

elseif numYears == 50

Put “Golden” to output

else Put “Congrats” to output

Put “\nBye” to output

3.10 Code: More branches

Nested if-else statements

An if-else statement has two branches. A branch’s statements can include any valid statements, including another if-else statement, known as nested if-else statements (or nested branches). The nested if-else statements can take on various forms, and the if-else statements may even use different variables.

3.11 Branches summary

This chapter’s key points included:

  • In a flowchart, a decision creates two branches, one for when the decision’s expression is true (the if branch), another when false (the else branch).
  • If-else branches have statements in each branch. An if branch has no statements in the else branch.
  • If-elseif branches have cascaded decisions along the false branches. Only one true branch can execute.
  • A branch can itself have a decision, known as nested branches.
  • Multiple if branches can be created, which are independent, so more than one true branch can execute.
  • Valid equality and relational operators are ==, !=, <, <=, >, >=.
  • If-elseif branches are commonly used to detect ranges, with the lower end of the range implicit.
  • Logical operators are: and, or, not.
  • In an expression, operators are evaluated in a specific order based on precedence rules (just like in math).
  • Because floating-point numbers aren’t represented exactly, they shouldn’t be compared for equality (using ==). Instead, they can be compared for “close enough”.
  • Branches in pseudocode use words like if, else, and elseif, and a branch’s statements appear indented starting on a next line.


Leave a Reply

Your email address will not be published. Required fields are marked *