Cheat sheets

AP Computer Science A / Chapter 2

Selection and Iteration

Cheat sheet

Decisions and repeated work

  • A decision chooses a path. A loop revisits a body. Processing an input and advancing to the next input are separate responsibilities.
  • Place observations at the required time; recording before a state change can produce a different result from recording afterward.

Comparisons

  • Numeric relations return boolean. == compares equality; = assigns. <= and >= include the boundary, while < and > exclude it.
  • A mixed int/double comparison widens the int. Reference == compares identity rather than an object’s contents.

Selection structure

  • Braces group a body; indentation does not. A braceless if controls one following statement.
  • if-else chooses one alternative. An else-if chain chooses its earliest successful branch, while independent if statements can each execute.
  • An else pairs with the nearest unmatched if. A nested test is reached only along its containing path.

Compound decisions

  • NOT has precedence over AND, which has precedence over OR. Parentheses make a different intended grouping explicit.
  • False-left AND skips the right operand; true-left OR skips it. Put a receiver-existence or nonzero-divisor guard before the protected operation.
  • Negating AND gives OR of the negated operands. Negating OR gives AND of the negated operands. Negate equality at each numeric boundary as well.
  • A truth-table disagreement in one input combination disproves equivalence; several agreeing rows do not establish it.

Identity and equivalence

  • Copied references identify one shared object. Separately constructed Strings can have matching contents without matching identity.
  • String equals compares characters. A reference can be compared safely with null, but null cannot receive an instance-method call.

Pretested repetition

  • A while test occurs before every potential body visit. An initially false condition produces zero visits.
  • Track the last successful test, its completed update and the final false test separately. The exit value can overshoot the written bound.
  • Termination requires progress toward a failing condition. An omitted or wrongly directed update can preserve a true condition.

Counted loops

  • A for executes initialization once, then test, body, update and another test. Header-declared control variables are unavailable after the loop.
  • To translate into while, initialize before the loop and put the update after the original body. Preserve the exact bound and observation order.

Numeric summaries

  • Initialize sums and counts before repeated work. Update a frequency count when its predicate succeeds.
  • An extremum candidate may start with an included reading or a valid bound for all permitted inputs. A fixed zero candidate fails for some all-negative or all-positive streams.
  • Compute a fractional mean by widening before division and require a positive count. Zero remainder by a nonzero divisor identifies divisibility.

Decimal digits

  • For positive integers, remainder by ten selects the final digit; integer division by ten removes it. Inspect before removing.
  • Internal zeros still receive visits. Input zero needs separate handling when a digit-count method permits nonnegative inputs.

Text algorithms

  • A character interval at i uses substring(i, i + 1) with i below length. A k-character interval permits a start through length minus k inclusively.
  • A step-one search counts overlapping matches. A flag for any match retains true after a witness is found.
  • Prepend while scanning forward, or append while scanning backward, to reverse text. Retain each returned concatenation; Strings remain immutable.

Nested work and counts

  • Each outer visit completes its inner traversal. An inner for header reinitializes per outer visit; an externally declared while counter does not reset itself.
  • Multiply fixed rectangular dimensions; add actual row counts for dependent bounds. Place per-row output after the inner loop inside the outer body.
  • Count the specific statement requested. A terminating pretested loop evaluates its condition once more than its body executes.
  • A fixed inner length leaves linear growth in the outer input; two input-sized dimensions produce square growth. Counts alone do not establish exact elapsed time.

Sign in