Loops – Comprehensive Study Notes

Loop Concept

  • A loop is a program construct that repeatedly executes a list of statements (the loop body) while a Boolean expression (the loop condition) is true\text{true}.

    • When the expression becomes false\text{false}, control proceeds to the first statement after the loop.

    • Each execution of the body is called an iteration.

  • Real-life analogy: Parents driving a baby “around the block” until the baby falls asleep.

    • Decision point: each time the car reaches a landmark (top or bottom of the street) parents check Awake?

    • If baby is awake \Rightarrow drive another loop; if asleep \Rightarrow exit.

  • Key vocabulary

    • Loop body – statements inside the loop.

    • Loop condition / expression – Boolean test that controls repetition.

    • Iteration – one pass through the body.

    • Sentinel – special value that signals loop termination when processing lists.

Loop Basics

  • Structure (generic):

  initialization
  while (expression) {      // decision statement
      statements            // loop body
      update                // prepares next test
  }
  continuation
  • Three canonical components for a counter-controlled (N-times) loop:

    1. Initialization of loop variable (before loop).

    2. Condition using relational operator (top of loop).

    3. Update of loop variable (end of body).

  • Once control enters the body, execution continues to the body’s end even if the expression would become false mid-body (one-entry, one-exit discipline).

  • Flow-chart example (powers of 2 until user enters 0):

    • Variables: curPower=2\text{curPower}=2, userNum=input\text{userNum}=\text{input}.

    • Condition: userNum==1\text{userNum}==1 \rightarrow print curPower\text{curPower} \rightarrow curPower=curPower×2\text{curPower}=\text{curPower}\times2 \rightarrow get next input.

Loop Examples

Summation & Average with Sentinel

  • Task: read non-negative integers terminated by 1-1, output average.

    • Initialize: sum=0\text{sum}=0, num=0\text{num}=0, val=input\text{val}=\text{input}.

    • Condition: \text{val} > -1.

    • Body:

    • sum=sum+val\text{sum}=\text{sum}+\text{val}.

    • num=num+1\text{num}=\text{num}+1.

    • val=input\text{val}=\text{input} (get next).

    • After loop: avg=sumnum\text{avg}=\dfrac{\text{sum}}{\text{num}}.

  • Critical points from participation Q&A:

    • First input fetched before loop; if negative, body never runs.

    • sum\text{sum} initialized to 00; each iteration adds the current input value.

    • num\text{num} counts how many actual values processed (not sentinel).

Counting Negatives

  • Goal: count how many negative numbers appear in a list ending with 00.

    • Condition (A) should be \text{val} < 0.

    • Counting statement (B): count=count+1\text{count}=\text{count}+1 when negative detected.

Finding Maximum in a Positive List (ending with 0)

  • Initialize max=1\text{max}=-1 so that every positive input is >\text{max} first time.

  • Condition: \text{val} > 0 (loop until 0).

  • Update rule (B): if \text{val} > \text{max} then max=val\text{max}=\text{val}.

  • Order of inputs does not affect final max.

Looping Until Done (User-Controlled)

  • Pattern: get initial input before loop, repeat body, get new input at end.

  • Celsius to Fahrenheit example

    • Menu choice userChoice\text{userChoice} controls continuation; loop exits when choice 1\neq 1.

    • Each iteration: output current celsiusValue\text{celsiusValue} and computed fahrenheitValue\text{fahrenheitValue}, then increment Celsius by 55.

    • Loop iterates at least once because initial value forces true.

Loop Expressions & Relational Operators

  • Common relational forms: <, \le, >, \ge, ==, \neq.

  • Design rule: expression describes when to iterate, not when to stop.

  • Practice prompts:

    1. Iterate while cVal==5\text{cVal}==5 \Rightarrow expression cVal==5\text{cVal}==5.

    2. Iterate while x < 100, x0x \ge 0, cVal10cVal \neq 10, etc.

  • Horizontal bar chart program: subtract 1010 per loop to print one “-”.

Common Loop Errors

  • Reversed condition (using ==0==0 instead of 0\neq0).

  • Forgetting to update loop variable \Rightarrow infinite loop.

  • Missing new input in body also causes infinite loop (example with doubling numKids\text{numKids}).

  • Detecting infinite loops: Coral simulator stalls or floods output; user must Pause/Exit.

Looping NN Times

  • Typical for counter variable ii starting at 00.

    • Condition for 10 iterations: i<10 (values 090\dots9).

    • For 99 iterations starting at 11: init i=1i=1; condition i<=99.

  • Savings account example

    • For loop executes 10 times, printing balance each year.

    • Each pass: output currSavings\text{currSavings}, then update currSavings=currSavings×(1+interestRate)\text{currSavings}=\text{currSavings}\times(1+\text{interestRate}).

More Complex Examples

Euclid’s GCD (while version)

  • If \text{numA}<\text{numB} swap.

  • Loop while \text{numA} \bmod \text{numB} > 0:

    • rem=numAmodnumB\text{rem}=\text{numA} \bmod \text{numB}.

    • numA=numB\text{numA}=\text{numB}; numB=rem\text{numB}=\text{rem}.

  • When remainder =0=0, numB\text{numB} (or numA\text{numA}) is GCD\text{GCD}.

Generational Ancestor Counter

  • Start curYear=2020\text{curYear}=2020, numAncestors=2\text{numAncestors}=2.

  • Loop while curYearuserYear\text{curYear} \ge \text{userYear}.

    • Output curYear:numAncestors\text{curYear}: \text{numAncestors}.

    • numAncestors=2×numAncestors\text{numAncestors}=2\times\text{numAncestors} (each ancestor has 2 parents).

    • curYear=curYear20\text{curYear}=\text{curYear}-20 (one generation back).

Temperature Table (-10 to 40 by 5)

  • For \text{currC}=-10; \; \text{currC}<=40; \; \text{currC}+!+=5:

    • F=95×currC+32\text{F}=\dfrac{9}{5}\times\text{currC}+32.

    • Print table row.

Nested Loops

  • Inner loop executes fully for each outer-loop iteration.

  • Bar-chart example: outer while reads value; inner for prints that many asterisks.

  • Counting inner executions: outerIterations×innerIterations\text{outerIterations}\times\text{innerIterations}.

Programming Constructs for Loops

while Loop

  • Syntax (C-style):

  while (condition) {
      // body
  }
  • Use when number of iterations cannot be determined a priori (e.g., sentinel, user quits with 'q').

do-while Loop

  • Guarantees at least one execution.

  do {
      // body
  } while (condition);
  • Example variable curCount\text{curCount} increments before first test.

for Loop

  • Compact counter-controlled form:

  for (i = start; i < end; i = i + step) {
      // body
  }
  • Preferred when iterations pre-computable (loop 100 times, loop numItems\text{numItems} times).

  • Every for can be rewritten as equivalent while; choose for readability.

  • Example transformations shown side-by-side in transcript.

Choosing Loop Type (Guidelines)

  • Pre-known count \Rightarrow for.

  • Unknown until runtime / sentinel / convergence \Rightarrow while.

  • Need at least one run regardless \Rightarrow do-while.

Code Patterns & Conversions

  • Converting for \rightarrow while:

  for (i=0; i<N; i++) {...}
  // equivalent
  i = 0;
  while (i < N) {
      ...
      i = i + 1;
  }
  • Loop to iterate userNum\text{userNum} times after reading input \Rightarrow use for.

  • Loop to keep halving userNum\text{userNum} until result < 10 \Rightarrow use while (condition unknown in advance).

Lab Overviews (Tasks to Practice)

  • Convert integer to binary by repeatedly outputting x%2x \% 2, updating x=x/2x=\lfloor x/2 \rfloor.

  • Read arbitrary non-negative integers, output average (integer division) and max, sentinel <0.

  • Output range [first, second] in steps of 1010, with error if second < first.

  • Countdown from 20–98 until both digits equal (e.g., 93,92,,8893,92,\dots,88); validate input range.

Loops Summary (Key Points)

  • Loops let programs process data repetitively: averages, counts, maxima.

  • Infinite loops arise from incorrect conditions or missing updates.

  • Counter-controlled loop requires init, condition, update.

  • while, do-while, and for offer specialized syntax but equivalent power.

  • Nested loops enable multi-dimensional tasks (tables, charts).

  • Choosing the correct loop type improves readability and maintainability.