Applied Programming/Loops

This lesson introduces loops, including while, for, and do loops.

Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Construct and analyze code segments that perform iteration
    • while; for; break; continue; pass; nested loops and loops that include compound conditional expressions

ReadingsEdit

  1. Wikipedia: Control flow

MultimediaEdit

Loop ConceptsEdit

  1. YouTube: Introduction to Programming - Iteration
  2. Youtube: While Loop Mistakes
  3. Youtube: Loops and Iterations - For/While Loops

Python LoopsEdit

  1. YouTube: Python 3 Programming Tutorial: While Loop
  2. YouTube: Python 3 Programming Tutorial - For loop
  3. Youtube: Python Nested For Loops

ExamplesEdit

ActivitiesEdit

  1. Extend the BMI program from the previous lesson. Rather than terminating the program on invalid input, display an error message and ask the user to enter valid input. Provide a way for the user to terminate the program instead if they choose.
  2. Extend the BMI program above. Add a loop to the main program that continues asking for input after displaying each BMI result. Provide a way for the user to terminate the program instead if they choose.
  3. Update program and function documentation, consistent with the documentation standards for your selected programming language.
  4. Extend the BMI program to displays a BMI table, with columns for height from 58 inches to 76 inches in 2-inch increments and rows for weight from 100 pounds to 250 pounds in 10-pound increments. Reuse the conversion/calculation functions from the BMI program above. Include appropriate program and function documentation, consistent with the documentation standards for your selected programming language.

Lesson SummaryEdit

  • For loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly.[2]
    • For-loop is known by a clear loop counter or loop variable which allows the body of the for loop to be repeatedly executed.[2]
    • For loop is typically used when the number of iterations is known before entering the loop.[2]
    • For-loop is commonly the source of an infinite loop since the fundamental steps of iteration are completely in the control of the programmer.[2]
  • Foreach loop means "do this to everything in this set", rather than "do this x times" which is what the traditional for loop means.[3]
    • Foreach loops usually maintain no explicit counter.[3]
    • Foreach loop avoids logical error and makes code simpler to read.[3]
    • An optional step-value could be an increment or decrement may also be included in for loop.[2]
  • When using a count-controlled loop to search through a table, it might be desirable to stop searching as soon as the required item is found. Some programming languages provide a statement such as break, which terminates the current loop immediately, and transfers control to the statement immediately after that loop.[4]
  • A loop variant is an integer expression which has an initial non-negative value.[4]
  • A loop invariant is an assertion which must be true before the first loop iteration and remain true after each iteration.[4]
  • Modern languages have a specialized structured construct for exception handling which does not rely on the use of GoTo or multi-level breaks or returns.[4]
  • Do-while loop is an exit-condition loop. This means that the code will enter the loop and then the condition will be evaluated, unlike while loops.[5]
  • A loop (like a Do-while loop) which checks its' condition after the execution of the loop body is called a post-test loop.[5]
  • A do-while loop is executed at least once and may continue to loop multiple times given the condition is true. It will loop until the given condition becomes false. In other words, in the event it doesn’t, an infinite loop will be created.[5]
  • Some languages use a different naming convention for this particular type of loop such as repeat until, while true, repeat while, and exit when.[5]
  • Often break statements are used with infinite loops to allow for termination.[5]
  • As long as the system is responsive, an infinite loop can be aborted in terminal or task manager with the Control-C command.[6]
  • Continue statements suspend the current iteration and then resume as normal with the next iteration. If the iteration is the last one in the loop, the statement will end the entire loop early.[4]

Key TermsEdit

break
A keyword available in most languages (the functionality is near-ubiquitous regardless) that exits the innermost loop structure.[4]
continue
A keyword that suspends the current iteration and jumps directly onto the next.[4]
do-while loop
A post-test loop, meaning the body is guaranteed to execute at least once, as the condition is evaluated after the fact. Often post-test loops are indefinite loops, which iterate until a sentinel value gets encountered.[5]
for loop
A specialized loop for iterating a given number of times (definitely), usually featuring an encapsulated head of initialization, Boolean, and incrementation (or decrementation) components.[2]
for-each loop
A take on the for loop, where the definite iteration can occur directly over a collection or sequence of data, e.g. a list or an array, avoiding the possibility of an off-by-one error.[3]
infinite loop
A common pitfall where the user is locked into a never-ending process because of an unsatisfied terminating condition.[7]
loop counter
The variable that controls the iterations of a loop.[2]
nested loop
A loop that is enclosed by an outer, surrounding loop, useful when it has two or more dimensions of elements to parse.[4]
pass
The pass statement is used as a placeholder for future code. It does nothing but avoid an error being thrown.[8]
raise
Allows the user to throw an exception at any time. If no expressions are present, the raise statement re-raises the last expression that was raised in the current scope.[9]
sentinel
A value that signals the completion of a process. An example is the EOF (end-of-file) marker present in many languages, representing not another character to read, but the end of the file and thus its processing.[10]
while loop
A pre-test loop, meaning there is no guarantee the body will execute. Like their do while counterparts, these loops are usually indefinite loops, iterating until a sentinel value gets encountered.[11]

See AlsoEdit

ReferencesEdit