Chapter 4 – Loops Comprehensive Study Notes

4.1 Loop Concepts and Motivation

  • Core metaphor
    • Parents driving a baby around the block until the baby sleeps illustrates repeating the same action until a condition becomes false ("baby is awake → keep driving").
    • Decision point can be before or after each iteration (top vs. bottom of the street).
  • Terminology
    • Loop body – statements that run repeatedly.
    • Loop expression / decision expression – Boolean test checked each time.
    • Iteration – one full execution of the body.
  • Q&A highlights from activities
    • First baby check: baby was awake → loop begins.
    • Number of loops equals the count of times the parents circled until the expression "baby-awake == True" became False.
    • Decision point location affects whether the loop executes at least once.

4.2 Loop Basics and Control Flow

  • Flowchart anatomy (example: doubling powers of 2 until user enters 11)
    • Initialization: curPower = 2, userNum = Get next input.
    • Loop expression: userNum == 1 (iterates while true).
    • Body: print power, newline, double curPower, get new input.
  • Key rules
    • Expression is evaluated before running the body in a while/for loop.
    • Once inside the body, statements run to completion even if the expression would switch to false part-way.
    • Common “loop-until-done” pattern: ask user at end of body whether to continue.
  • Celsius→Fahrenheit example
    • Conversion: F=(C×9.0/5.0)+32.0F = (C \times 9.0 / 5.0) + 32.0.
    • userChoice controls continuation; loop always iterates at least once because userChoice initially set to 11.
    • Each pass adds 55 to celsiusValue.
  • Getting input before and after loop – avoids dummy initialization.

4.3 More Loop Examples (Sentinel Values & GCD)

  • Sentinel value – special terminator not processed in the computation (e.g., list ends with 00 or 1-1).
  • Average until sentinel
    • Variables: sum, num, val.
    • Pseudocode:
    1. val = Get input (may be sentinel).
    2. while val > -1 → add to sum, increment num, get next.
    3. After loop: avg = sum / num.
  • Counting negatives
    • count starts at 00; increment whenever val < 0.
  • Finding maximum
    • Initialize max = -1; for each positive val, if val > max then max = val.
    • Order of inputs does not affect final max.
  • Euclid’s GCD
    • Ensure numAnumBnumA \ge numB; if not, swap.
    • Loop while numA % numB > 0
    • rem = numA % numB
      numA = numB
      numB = rem
    • Finishes with both variables equal to gcd(numA<em>0,numB</em>0)\gcd(numA<em>0,numB</em>0).

4.4 Looping NN Times

  • Pattern (while version)
    1. Initialization: i = 0.
    2. Expression: i < N.
    3. Update: i = i + 1 (at end of body).
  • Savings-with-interest example
    • For 1010 years: currSavings = currSavings * (1 + rate) then print.
    • Rate might be expressed as percent/100.
  • First input counts list length
    • Example input: 4 10 1 6 3 → loop iterates 44 times.

4.5 Loop Examples Beyond Simple Counting

  • Output sequences by tweaking the three parts
    • Multiples of 55 from 1010 to 5050: init i=10i = 10, expression i50i \le 50, update i=i+5i = i + 5.
    • Temperature table 10-104040 step 55 using variable currC.
  • Data analysis pattern
    • Maintain running statistic (sum, max, count) updated each iteration.

4.6 Choosing While vs For

  • Heuristic table
    • Number of iterations known before loop → for.
    • Iterations depend on data encountered during loop → while.
  • Examples
    • “Iterate 100 times” → for.
    • “Read until user enters 0” → while.

4.7 Nested Loops

  • Definition: loop inside another loop (outer vs. inner).
  • Bar-chart example
    • Outer while reads next integer (terminates on negative).
    • Inner for prints one * per unit of magnitude.
  • Counting inner executions = (#outer iterations) × (#inner iterations per outer pass).

4.8 Code Representation: while

  • General syntax (C-style pseudocode)
  while (expression) {
      // body
  }
  • Converting flow-chart to code: move initialization above, update at bottom.
  • Ancestors example revisited in pure code
  curYear = 2020;
  numAnc = 2;
  while (curYear >= userYear) {
      print(curYear, numAnc);
      numAnc = numAnc * 2;
      curYear = curYear - yearsPerGen; // 20
  }
  • Infinite-loop pitfalls
    • Missing update statement.
    • Using wrong operator (== vs. !=).
    • Example that forgets to re-read userNum results in endless doubling of numKids.

4.9 Code Representation: do-while

  • Syntax (executes body before expression check)
  do {
      // body
  } while (expression);
  • Use case: loop must run at least once (e.g., prompt user, then decide to repeat).
  • Example variables: curCount, userNum; counting runs until userNum <= 4.

4.10 Code Representation: for

  • Syntax
  for (init; expression; update) {
      // body
  }

Equivalent while:

  init;
  while (expression) {
      // body
      update;
  }
  • Iteration values
    • for i = 0; i < 6; i = i + 1ii takes 0,1,2,3,4,50,1,2,3,4,5.
    • Loop count = difference between bounds when using ++.
  • Looping variable names should be descriptive (e.g., currYear, currC).
  • Savings-interest & average examples re-implemented with for.

4.11 Loops Summary & Best Practices

  • Always identify the three critical parts: init, expression, update.
  • Select loop type for readability: for when countable, while otherwise, do-while when at least one iteration is mandatory.
  • Guard against infinite loops by ensuring the expression can become false and updates occur.
  • Nested loops multiply work; reason about total iterations.
  • Use sentinel values to process unknown-length input cleanly.

4.12–4.15 Programming Labs Overview

  • 4.12 Convert to Binary
    • Loop while x > 0; output x%2x \% 2; divide x=x/2x = x / 2 (reverse order of bits).
  • 4.13 Varied Amount of Input Data
    • Read non-negative integers until negative sentinel.
    • Maintain running sum, count, max; after loop output sum/count\lfloor sum / count \rfloor and max.
  • 4.14 Output Range with +10
    • Inputs low, high; if low > high output error message, else loop value += 10.
  • 4.15 Countdown Until Matching Digits
    • Input between 20209898 inclusive.
    • While the two digits differ, print number, decrement by 11.
    • Reject input outside range.