menu-button

Arithmetic & Boolean Operators

Introduction

In the slides above, we learned that:

  • Arithmetic operators input two numbers and output a number. e.g. 3 + 4 will evaluate to 7. Use * for times, / for divide and either x ** y or Math.pow(x,y) for ||x^y||.
  • A particularly important arithmetic operators is the modulus function, which allows us to get the remainder from a division. e.g. 18 % 7 will evaluate to 4. We can use this to see if one number is a multiple of another, e.g. n % 3 == 0 will be true if n is a multiple of 3. We can therefore use the mod function for determining if an integer is odd or even.
  • Comparison operators compare two numbers in some way, and return a boolean (true or false). 3 <= 4 for example will evaluate to true.
  • Do not mix up = (assignment) and == (test of equality). x = 5 assigns x the value 5, whereas x == 5 will test whether the current value of x is equal to 5, and return true if it is.
  • Boolean operators allow us to combine boolean values. a && b is true if both a and b are true. a || b returns true if either a or b are true (or both are true). !a is negation, and return true if a was false, and vice versa.
  • x++ is a convenient way of writing x = x + 1. Note that x++ is also an expression (i.e. returns a value): x++ increments x by 1 but returns the original value of x, whereas ++x increments x but returns the new value of x.

Mini Task #1: Arithmetic Operators

Which of the following expressions will evaluate to 5?

Mini Task #2: Boolean Operators

For each of the following, replace yourExprHere with a suitable boolean expression in terms of a and b (and possibly c), that matches the description given.

"Returns true if a and b are both true, or both false. Otherwise returns false."

Reset to Original Code     Fullscreen

"Returns true if a or b are true, but c is not true. Otherwise returns false."

Reset to Original Code     Fullscreen

Mini Task #3: Comparison Operators

If a = 5 and b = 15, which of the following evaluate to true?

Mini Task #4: Factors and Multiples

This function takes two values: m and n, and should output true if m is a factor of n, and false otherwise. Note that the final line of code just before the } line should be "return yourValueGoesHere".

Reset to Original Code     Fullscreen

Mini Task #5: Boolean Challenge

This function takes three values: a, b, c and d and should output true only if exactly 2 of the four of them are true. Can you do it without having to consider all possible combinations? (hint: is there an arithmetic operator which will coerce your inputs to another more useful type?). Note that the final line of code just before the } line should be "return yourValueGoesHere".

Reset to Original Code     Fullscreen