ICS2O Page 1
Arithmetic Operators & Expressions
An arithmetic expression is a combination of numeric values (literals), variables, and operators that result in a
numeric value.
https://www.khanacademy.org/computing/computer-programming/programming/resizing-with-variables/a/using-math-expressions-in-js
A literal is a value (number, letter, character, string, etc.) typed directly into a program.
Examples (with poor variable naming)
var a = 9; // 9 is a numeric literal (integer)
var b = 10.0; // 10.0 is a numeric literal (floating point / decimal)
var x = ‘h’; // ‘h’ is a character literal
var y = “Hi”; // “Hi” is a string literal
var t = false; // false is a Boolean literal
Question
What two operations are taking place in each of the above statements? _declaration__ and _assignment_.
Operators
An operator is a special symbol for performing a function that combines values and/or expressions.
An operand is one of the things that gets combined (i.e. the values or expressions being operated on).
5 * 4 Operator(s): _________ Operand(s): _________
0.7 / 4.5 Operator(s): _________ Operand(s): _________
Integer & Floating-point Operators
Addition: + Subtraction: – Multiplication: * Division: / Remainder (Modulus): %
• Modulus returns the remainder of a division operation (e.g. 8 % 3 = 2).
• The usual order of operations applies, with modulus having the same priority as multiplication and division.
In Computer Science, the order of operations is called operator precedence.
BEDMAS!
Examples (try them yourself, check answers in a program on Khan Academy)
5 + 3 * 2 = _____ (3 – 4) * 5 = _____ 14 / 3 = _____ 14 % 3 = _____
var a = 27 / 5 * 3 – 45 / 2; var b = 90 + 45 % 4 – 15 / 2;
What value gets assigned to a? _____ What value gets assigned to b? _____
Integer and floating-point operands can be mixed, resulting in a floating-point (decimal) value.
Practice – Evaluating Arithmetic Expressions (try them yourself, check answers in a program)
Expression Result (Value) Type (integer or floating point)
4.5 * 2 – 5 = 9 - 5 4 integer
4.5 * (2 – 5)
5 / 4 + 9.0
0 * 15 / 2
10 % 4 + 4
10 % 1.5 + 4
ICS2O Page 2
Concatenation (String Addition)
The + operator has dual meaning. Depending on how and where it is used, it can be used to perform numeric
(mathematical) addition or string addition (i.e. concatenation). You can “add” strings with numbers (integers or
floating-point) using the + operator. This will concatenate them (add them together as strings). If at least one of
the operands is a string, the result will be a string as well. Be careful when performing concatenation, as some
unexpected results can occur.
Example Can you explain what is happening here and why?
text(“23 + 7 = ” + 23 + 7, 10, 10); vs. text(23 + 7 + “ = 23 + 7”, 10, 10);
Output: 23 + 7 = 237 30 = 23 + 7
More Examples (“_” means a space): use b (a ‘b’ with a forward slash through it) to represent spaces
“hello_” + “dolly” = ____________ 50 + “_cent” = _________
“JS_” + “5.” + 4.2 = __________ “2” + 2.0 = ______ 2 + 2.0 = _____
Operations with Strings (Operators & Methods)
There are many other operations that can be performed on or with strings, but they are done using pre-defined
(built-in) functions:
• String length (returns the number of characters in the string): stringName.length
• Convert all letters to lower case (returns the string in all lower case): stringName.toLowerCase()
• Convert all letters to upper case (returns the string in all upper case): stringName.toUpperCase()
• Returns the character at the given index/position in the string: stringName.charAt(index)
• Returns the substring starting at the given position/index: stringName.substring(index)
• Returns the substring between the given start and end positions/indices
(includes character at start, but excludes character at end): stringName.substring(start, end)
Note: all indexing of strings starts at 0 (i.e. the position or index of the first character in a string is 0)
Examples
var toy = “yoyo”; var words = “The quick brown fox”;
toy.length = ________ words.charAt(4) = _____
toy.length + 2 * 3 = ________ words.charAt(4).toUpperCase() = _____
toy.toUpperCase() = ____________ words.substring(10) = _______________
words.substring(4, 13) = _______________
Rounding & Other Math-related Functions
round(num): rounds a number to the nearest integer
round(5.6) = _____ round(7.4) = _____
Using round() to round a value to any number of decimal places:
round(345.678912 * 10) / 10 = ______________ → rounds to ______ decimal places.
round(345.676912 * 1000) / 1000 = __________ → rounds to ______ decimal places.
floor(num): rounds a number down to the nearest integer
floor(6.9) = _____ floor(17.3) = _____
ceil(num): rounds a number up to the nearest integer
ceil(6.9) = _____ ceil(17.3) = _____
ICS2O Page 3
random(low, high): generates a random number between low (inclusive) and high (exclusive)
random(1, 100) = a random number between 1 and 99.9999...
floor(random(1, 7)) = a random integer between 1 and 6 (like a die roll)
For a random fill colour,
fill(floor(random(0, 256)), floor(random(0, 256)), floor(random(0, 256)));
pow(base, exponent): calculates a power, the base raised to the exponent (baseexponent)
pow(2, 3) = _____ pow(7, 2) = _____
sqrt(num): calculates the positive square root of any non-negative number (to 3 decimal places)
sqrt(25) = _______ sqrt(35) = _______ sqrt(-1) = _____
What is the meaning of NaN?
min(num1, num2) and max(num1, num2): determines the minimum or maximum of two values
THINK: How can we find the max. or min. of more than 2 values?
The value of can be retrieved with the pre-defined variable:
PI = 3.1415926535...
There are also functions for the three primary trigonometric functions:
sin(value) cos(value) tan(value)
There are many other useful functions built into the Processing.JS language:
Get the current date with: day(), month(), year()
day() for the day of the month, month() for the number of the current month (1 to 12), year() for the year
Get the current time with: hour(), minute(), second()
Get the time (in milliseconds) that has elapsed since the program started with: millis()
Variables in Expressions
Anywhere you can put a literal, you can also put a variable.
Examples (with poor variable naming)
var d = 8.9, d2 = -0.5, i = -6;
d + d2 * i = _____ floor(d) * i + 3 = _____
round(d) * d2 = _____ i * i = _____
var x = d2 * i + i;
What value is stored in variable x after these statements? x = ______
x = x + 1;
NOTE – Two Special Operators
The last statement in the examples above (x = x + 1;) can be written in a shorter way using one of the special
“Prefix/Postfix” operators in Java. These operators will increase or decrease the value of a variable by 1:
x++; __________________ x--; __________________
ICS2O Page 4
Practice Programs
1. Bank Interest: Write a short program that asks the user their bank balance and interest rate, then calculates
the interest on their current balance to the nearest cent and displays the result rounded to two decimal places.
Make the output look nice. Name your program: <LastName>BankInterest
• Plan out your solution before coding by writing pseudo-code to describe the algorithm (the steps necessary
to perform the task). Include all the steps required to perform input, processing, and output.
• In small groups (2 to 4), examine and compare your pseudo-codes and try to come up with a consensus
solution. Then, write the program as a group.
→ Refer to file/handout “Analysis & Design of a Program.doc” for more detailed info and instructions.
2. Rectangle Calculator: Write a program that asks the user for a length and width in pixels, then draws the
rectangle, and outputs the perimeter (in pixels) and area (in pixels squared). Name your program:
<LastName>RectangleCalculator
Rectangle Calculator!!! Example
output…
Enter the length in pixels: 56
Enter the width in pixels: 34
<clear screen>
Your rectangle has a perimeter of 180 pixels and an area of 1904 pixels squared.
3. Hollow Square Calculator: Write a program that asks the user for a radius in pixels,
then uses the given radius to draw an image with a square and a circle like the one on the right, r
and then calculates and outputs the area of the shaded portion rounded to the nearest square
pixel. Name your program: <LastName>HollowSquareCalc
2r
Hollow Square Calculator!!! Example
output…
Enter the radius in pixels: 200
<clear screen>
Your hollow square has an area of 34336 pixels squared.