Variables, Expressions, and Data Types – Comprehensive Study Notes chapter 2
Variables and Assignments
- A variable = named storage location that holds a value until reassigned.
- Notation: x, numPeople, userAgeYears, etc.
- Box analogy: think of a labelled box whose content can be replaced.
- Assignment statement: variable=expression
- Left side must be a variable; right side can be literal, variable, or any valid expression.
- Read as “is assigned with”, NOT “equals”.
- Examples
- x=5
- y=a (copies a’s current value)
- z=w+2
- Overwriting: new assignment replaces old value until another assignment occurs.
- E.g. x=6 then x=x+1 → x=7, old 6 lost.
- Variable can appear on both sides: count=count−1, balance=balance∗1.05.
- Important invalid forms
- 5=x ❌ (left side not variable)
- x+y=5 ❌ (left side expression, not variable)
Identifier Rules & Naming Conventions
- Valid characters: letters, digits, underscore; must start with a letter.
- Case-sensitive: numCats ≠ NumCats.
- Reserved words (integer, float, Get, Put, if, while, …) cannot be used.
- Style conventions
- lowerCamelCase: numApples, peopleOnBus.
- underscoreseparated: num</em>apples.
- Be meaningful & concise; avoid cryptic abbreviations and excessive length.
- Choose best identifier per purpose (e.g., numberOfJellyBeansInJar better than nmJlyBnsInJr).
Integer Variables & Declarations
- Declaration syntax (Coral):
integer userAgeYears. - Default initial value in Coral = 0.
- Range ≈ −2B to +2B (32-bit).
- Typical use: countable quantities (cars, pizzas, days).
Assignment Semantics & Tracing
- Example trace:
x = 3, y = 8, z = 8x = 2, y = 6, z = 0x = 9
Final: x=9,y=6,z=0.
- Participation activities reinforce manual tracking.
Expressions & Operators
- Expression = combination of literals, variables, operators, parentheses; evaluates to a value.
- Literals: integers (5), floats (3.14), strings ("Hi").
- Arithmetic operators
- Addition +
- Subtraction / Unary minus −
- Multiplication ∗
- Division /
- Modulo (integer remainder)
- Validity examples
- x+1 ✔️
- 2∗(x−y) ✔️
- 3x ❌ (implicit multiplication not allowed; must write 3∗x).
Precedence Rules & Parentheses
- Parentheses ()
- Unary minus (negation)
- ∗ and / (left→right)
- + and − (left→right)
- Good practice: add parentheses to clarify intent, e.g.
y = (m * x) + b. - Calories formulas (with explicit parentheses):
- Men: calories=((Age×0.2017)−(Weight×0.09036)+(HR×0.6309)−55.0969)×4.184Time.
- Women analogous with different constants.
Floating-Point (float) Numbers
- float = real number; decimal can “float”. Examples: 98.6, 0.0001, -666.667.
- Declaration:
float milesTraveled (default 0.0). - Typical use: measured values or fractions of counts.
- Literal style: always include leading digit (0.5 not .5).
- Output formatting:
Put var to output with N decimal places → rounds display only.- Example:
0.125 with 1 decimal → 0.1 (rounded).
- Scientific notation output possible: 2.99792e+08.
- Division by zero (float)
- Non-zero ÷ 0 → ∞ or −∞.
- 0 ÷ 0 → NotANumber.
Math Functions
- Built-in Coral functions:
- SquareRoot(x) → x.
- RaiseToPower(x,y) → xy.
- AbsoluteValue(x) → ∣x∣.
- Functions can be nested:
RaiseToPower(2.0, RaiseToPower(x, y) + 1). - Mass-growth example: finalMass=m0×(1+r)t using
RaiseToPower. - Pythagorean calculation uses chained calls.
Random Numbers
RandomNumber(low, high) → uniform integer in [low, high].- #values = high−low+1.
- Dice:
RandomNumber(1, 6). - Coin:
RandomNumber(0, 1).
- Pseudo-random: deterministic sequence seeded by
SeedRandomNumbers(seed).- Omit seeding → auto-seed via current time (different each run).
- Fixed seed useful for reproducible tests.
- Seat-moving example: pick row 1-20 and column sets 1-15 vs 16-30.
Integer Division & Modulo (%)
- Integer division / truncates toward 0.
- 10/4=2, 5/9=0.
- Float division occurs if either operand is float.
- Divide by zero (integer) → runtime error, program terminates.
- Modulo a%b returns remainder.
- 23%10=3, 70%7=0.
- Phone-number breakdown example uses
/ and % to split digits.
Type Conversion & Casting
- Implicit conversion (automatic)
- In mixed expression, int → float so operation is float.
- Assigning float to int → fraction truncated.
- Explicit cast: multiply int by
1.0 to force float before division.- Correct:
(1.0 * a) / b yields float. - Common error:
1.0 * (a / b) still performs int division first.
- Resulting type examples:
3 / 2 → int 1.3.0 / 2 → float 1.5.
Constants
- Constant = named immutable value.
- Syntax (conceptual):
const float SOUND_SPEED = 761.207.
- Convention: ALL_CAPS with underscores.
- Benefit: readability & single-point change (e.g.,
PRICE_DISCOUNT).
Data Types Overview
- Integer — whole numbers, counts.
- Float — real numbers, measurements.
- Boolean —
true / false states. - Character — single symbol.
- String — sequence of characters.
- Array — ordered list of same-typed items.
- Coral fully supports integer, float, array; Booleans arise from comparisons; strings as literals for output.
Example Programs & Incremental Development
- Health-data app developed in stages:
- Age in days: ageDays=ageYears×365.
- Add leap-year days: +⌊ageYears/4⌋.
- Convert to minutes:
* 24 * 60. - Estimate heartbeats: multiply by avg 72 bpm.
- Travel-time calculator: flying vs driving for input miles.
- Lightning-distance estimator using constants
SEC_PER_HOUR and SOUND_SPEED. - Numerous zyLabs: house pricing, caffeine decay (half-life), divide-by-x, driving costs, simple statistics, musical note frequencies, phone-number parsing.
Style Guidelines & Readability
- One statement per line; blank line separates declarations from executable code.
- Single space around operators (
a + b, not a+b). - Unary minus exemption:
x = -y. - Avoid “magic numbers”; use constants.
Common Errors & Pitfalls
- Confusing assignment with equality.
- Invalid left-hand side of
=. - Forgetting that
/ between ints truncates. - Casting result instead of operands.
- Omitting parentheses, relying on ambiguous precedence.
- Using
% or / with zero divisor. - Writing
3x instead of 3 * x.
Key Takeaways
- Think of variables as labelled containers; assignment updates contents.
- Master precedence rules but prefer explicit parentheses.
- Choose integer vs float based on count vs measure.
- Use built-in math & random utilities; seed for reproducibility.
- Employ constants and naming conventions for maintainable code.
- Understand type conversions to avoid subtle integer-division bugs.
- Practice incremental development and thorough testing.