Skip to main content

Chapter Summary

This chapter introduces iteration, the fundamental programming concept that allows programs to repeat code blocks. Together with selection, iteration forms the core methods to control the logical flow of programs. Iteration is essential because many real-world problems require repeating the same operations multiple times.

Key Concepts

  • While Loops

    • Used when the number of iterations is unknown in advance
    • Condition is checked before each iteration
    • Syntax: while (condition) { /* code */ }
  • For Loops

    • Used when the number of iterations is known in advance
    • Consists of three components: initialization, condition, and update
    • Syntax: for (init; condition; update) { /* code */ }
    • Standard counting recipe of a for loop that runs n times: for(i = 0;i<n;i++){/*code*/}
  • Do-While Loops

    • Executes the loop body at least once before checking the condition
    • Condition is checked after each iteration
    • Rarely used in practice and should generally be avoided in favor of while loops
    • Syntax: do { /* code */ } while (condition);
  • Loop Selection Guidelines

    • For loops: Known iteration count, counting operations
    • While loops: Unknown iteration count, repeating until some non-counting related condition is met
    • Do-while loops: Avoid, but the only situation where it may be useful is input validation, sentinel-controlled input
  • Loop Safety

    • Always ensure loops will eventually terminate
    • Avoid modifying loop counters within the loop body of a for loop, only modify in for() statement
    • Keep loop control logic simple and visible
    • Test loop conditions carefully to prevent infinite loops