2.1 Algorithms with selection and repetition · 2.2 Boolean expressionsQuestions with true or false answers

Every algorithm is built from three building blocks. Sequencing runs steps in order. Selection chooses which steps to run, based on a true-or-false test: "if it's raining, take the umbrella." Repetition, also called iteration, repeats steps while a test stays true: "while there are dishes in the sink, wash one." Combine the three and you can describe any algorithm at all.
?Wait, what's a boolean again?
The test is a Boolean expression: an expression whose value is true or false. The simplest ones use the relational operators, which compare two values: == (equal to), != (not equal to), <, >, <= and >=. Each comparison produces a boolean, which you can store, print or use as a test.
| Expression | Meaning | With x = 7, y = 10 |
|---|---|---|
| x == y | equal to | false |
| x != y | not equal to | true |
| x < y | less than | true |
| x > y | greater than | false |
| x <= 7 | less than or equal to | true |
| y >= 11 | greater than or equal to | false |
?Wait, what's the difference between = and == again?
Use == and != for primitive values: ints, booleans, and with care, doubles. Because doubles can carry round-off error, 0.1 + 0.2 == 0.3 is false. Use == on objects only when you really mean "is this the very same object?", which is topic 2.6.
I thought about it. Show me
With int a = 7 and int b = 2, evaluate each expression.
(a) a / b == 3 (b) a % b != 0 (c) a / 2.0 >= 3.5 (d) (a + b) % 3 == 0
- (a) a / b is 7 / 2, which is 3 (integer division). 3 == 3 is true.
Why?
Arithmetic happens before comparison. Work out each side first, then compare. - (b) a % b is 7 % 2, which is 1. 1 != 0 is true. (This is the test for "a is odd".)
- (c) a / 2.0 is 3.5, a double. 3.5 >= 3.5 is true, because >= includes equal.
- (d) a + b is 9, and 9 % 3 is 0. 0 == 0 is true. (This is the test for "a + b is a multiple of 3".)
Answer: All four are true.
Stuck? Get a hint
- Do the arithmetic on each side first. Remember 7 / 2 is 3 with ints.
- % gives the remainder: 7 % 2 is 1, 9 % 3 is 0.
- >= is true when the two sides are equal, too.
- An / 5 == 0
- Bn % 5 == 0
- Cn % 5 == 5
- Dn / 5 == 1
Show the answer
B. A multiple of 5 leaves no remainder when divided by 5, so n % 5 == 0. Choice A is the trap: n / 5 == 0 is true for 0 through 4, not for multiples of 5. The remainder of a division by 5 is never 5, so choice C is never true.
- Three building blocks: sequencing, selection (choose), repetition (repeat).
- Relational operators ==, !=, <, >, <=, >= produce a boolean.
- n % d == 0 tests divisibility. n % 2 == 0 tests even.
- Be careful with == on doubles (round-off) and on objects (that's "same object", topic 2.6).