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: xx, numPeoplenumPeople, userAgeYearsuserAgeYears, etc.
    • Box analogy: think of a labelled box whose content can be replaced.
  • Assignment statement: variable=expression\text{variable} = \text{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=5x = 5
    • y=ay = a (copies aa’s current value)
    • z=w+2z = w + 2
  • Overwriting: new assignment replaces old value until another assignment occurs.
    • E.g. x=6x = 6 then x=x+1x = x + 1x=7x = 7, old 6 lost.
  • Variable can appear on both sides: count=count1count = count - 1, balance=balance1.05balance = balance * 1.05.
  • Important invalid forms
    • 5=x5 = x ❌ (left side not variable)
    • x+y=5x + y = 5 ❌ (left side expression, not variable)

Identifier Rules & Naming Conventions

  • Valid characters: letters, digits, underscore; must start with a letter.
  • Case-sensitive: numCatsnumCatsNumCatsNumCats.
  • Reserved words (integer, float, Get, Put, if, while, …) cannot be used.
  • Style conventions
    • lowerCamelCase: numApplesnumApples, peopleOnBuspeopleOnBus.
    • underscoreseparated: num</em>applesnum</em>apples.
    • Be meaningful & concise; avoid cryptic abbreviations and excessive length.
    • Choose best identifier per purpose (e.g., numberOfJellyBeansInJarnumberOfJellyBeansInJar better than nmJlyBnsInJrnmJlyBnsInJr).

Integer Variables & Declarations

  • Declaration syntax (Coral): integer userAgeYears.
  • Default initial value in Coral = 0.
  • Range ≈ 2B-2\text{B} to +2B+2\text{B} (32-bit).
  • Typical use: countable quantities (cars, pizzas, days).

Assignment Semantics & Tracing

  • Example trace:
    1. x = 3, y = 8, z = 8
    2. x = 2, y = 6, z = 0
    3. x = 9
      Final: x=9,  y=6,  z=0x = 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+1x + 1 ✔️
    • 2(xy)2 * (x - y) ✔️
    • 3x3x ❌ (implicit multiplication not allowed; must write 3x3 * x).

Precedence Rules & Parentheses

  1. Parentheses (  )(\;)
  2. Unary minus (negation)
  3. * and // (left→right)
  4. ++ 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)×Time4.184\text{calories} = \big((\text{Age} \times 0.2017) - (\text{Weight} \times 0.09036) + (\text{HR} \times 0.6309) - 55.0969\big) \times \dfrac{\text{Time}}{4.184}.
    • 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 → \infty or -\infty.
    • 0 ÷ 0 → NotANumber.

Math Functions

  • Built-in Coral functions:
    • SquareRoot(x)\text{SquareRoot}(x)x\sqrt{x}.
    • RaiseToPower(x,y)\text{RaiseToPower}(x, y)xyx^y.
    • AbsoluteValue(x)\text{AbsoluteValue}(x)x|x|.
  • Functions can be nested: RaiseToPower(2.0, RaiseToPower(x, y) + 1).
  • Mass-growth example: finalMass=m0×(1+r)t\text{finalMass} = m_0 \times (1 + r)^{t} using RaiseToPower.
  • Pythagorean calculation uses chained calls.

Random Numbers

  • RandomNumber(low, high) → uniform integer in [low, high].
    • #values = highlow+1\text{high} - \text{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=210 / 4 = 2, 5/9=05 / 9 = 0.
  • Float division occurs if either operand is float.
  • Divide by zero (integer) → runtime error, program terminates.
  • Modulo a%ba \% b returns remainder.
    • 23%10=323 \% 10 = 3, 70%7=070 \% 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:
    1. Age in days: ageDays=ageYears×365\text{ageDays} = \text{ageYears} \times 365.
    2. Add leap-year days: +ageYears/4+ \lfloor\text{ageYears}/4\rfloor.
    3. Convert to minutes: * 24 * 60.
    4. 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.