Study Notes on Programming Logic and Design: Looping

Understanding the Advantages of Looping

  • Looping is a fundamental structure in computer programming that enhances efficiency and makes development worthwhile.

  • Through looping, a programmer can write one set of instructions to operate on multiple, separate sets of data.

  • Advantages of using loops include:

    • Less time required for the design and coding phases of development.

    • Fewer errors in the logic.

    • Shorter compile times for the program.

  • A loop is defined as a structure that repeats specific actions while a certain condition continues to be true.

  • Loops differ from dual-alternative (or binary) selection structures, which provide an action for each of two possible outcomes once, rather than repeating them.

Using a Loop Control Variable

  • A while loop’s body executes only as long as its governing condition remains true.

  • To control the number of repetitions, a loop control variable must be used.

  • There are three requirements for using a loop control variable effectively:

    1. The loop control variable must be initialized before entering the loop.

    2. The loop control variable must be tested in the loop's condition.

    3. The body of the loop must alter the value of the loop control variable so the condition can eventually become false.

  • Repetitions are typically controlled in two ways:

    • Counter: A numeric variable used to create a definite loop by counting occurrences. It usually begins with a value of 00.

    • Sentinel value: A specific value used to create an indefinite loop where the exact number of iterations is unknown until the program runs.

Definite and Indefinite Loops

  • Definite Loop:

    • This loop executes a predetermined, specific number of times.

    • It is often called a counter-controlled loop because the program counts repetitions.

    • Loop control variables in these loops are altered by incrementing (adding to the value) or decrementing (subtracting from the value).

    • Example: A counted while loop that outputs "Hello" exactly 44 times.

  • Indefinite Loop:

    • This loop is performed a different number of times each time the program executes.

    • The end of the loop is often determined by the user, who decides how many times the loop should execute.

    • Example: An indefinite while loop that displays "Hello" as long as the user wants to continue and has not entered a sentinel value to stop.

Three Steps in Mainline Loop Logic

  • Every properly functioning loop must involve three distinct steps concerning the loop control variable:

    1. Initialize: Provide a starting value for the variable that will control the loop.

    2. Test: Compare the loop control variable to determine whether the loop body should execute or terminate.

    3. Alter: Change the value of the loop control variable within the loop body to ensure the loop is not infinite.

Nested Loops

  • Nested loops occur when one loop is placed inside another loop.

  • Outer Loop: The loop that contains the second loop.

  • Inner Loop: The loop that is contained within the outer loop.

  • Nested loops are necessary when values of two or more variables must repeat to produce every possible combination of values, such as producing an "AnswerSheet" program for multiple questions and multiple students.

  • Key facts regarding nested loops:

    • Nested loops never overlap; the inner loop is always completely contained within the outer loop.

    • An inner loop completes all of its iterations each time the outer loop goes through just a single iteration.

    • The total number of iterations executed by a nested loop is the product of the number of inner loop iterations and the number of outer loop iterations (TotalIterations=InnerIterations×OuterIterationsTotalIterations = InnerIterations \times OuterIterations).

Avoiding Common Loop Mistakes

  • Neglecting to initialize the loop control variable:

    • If a variable like name is not initialized (e.g., a get name statement is removed), the value remains unknown or "garbage."

    • The program may terminate before any actions (like printing labels) occur, or it might print many labels (e.g., 100100 labels) with invalid data.

  • Neglecting to alter the loop control variable:

    • Removing the instruction to update the variable (e.g., removing a get name instruction inside the loop) prevents the user from entering new data.

    • This creates an infinite loop, where the structure can never terminate. An infinite loop is always logically incorrect.

  • Using the wrong comparison with the loop control variable:

    • Programmers must ensure the correct comparison operator is used (<, >, ==, etc.).

    • Errors in comparison can lead to serious real-world consequences, such as:

      • Overcharging an insurance customer by 11 month.

      • Overbooking an airline flight.

      • Dispensing extra medication to patients in a pharmacy.

  • Including statements inside the loop that belong outside:

    • A common mistake is placing a calculation inside a loop that remains constant for every iteration.

    • Example: Calculating a 30%30\% discount for every item by repeating the math inside a loop 100100 times for different prices. This is inefficient. Moving the calculation outside the loop (if possible) or ensuring only necessary actions are repeated improves performance.

Using the for Loop

  • The for statement (or for loop) is a specialized definite loop structure.

  • It provides three actions in a single structure: initialization, evaluation (testing), and alteration.

  • A for loop example logic: for count = 0 to 3 step 1 output "Hello" endfor.

    • It initializes count to 00.

    • It checks count against the limit value of 33.

    • If the evaluation is true, it executes the body (printing "Hello").

    • It increases count by the specified step value.

  • Step Value:

    • The amount by which the loop control variable changes during each iteration.

    • It can be positive (incrementing) or negative (decrementing).

    • The default step value is typically 11.

    • Programmers specify a step value when the loop control variable needs to change by a value other than 11.

Pretest vs. Posttest Loops

  • Pretest Loop:

    • The loop control variable is tested before every iteration.

    • Both while and for loops are categorized as pretest loops.

  • Posttest Loop:

    • The loop control variable is tested after each iteration.

    • The do...while structure is a posttest loop, meaning the loop body always executes at least once.

Common Loop Applications

  • Accumulating Totals:

    • Business reports often use loops to provide totals, such as a list of real estate sold and its total value.

    • Accumulator: A variable used to gather values. It is similar to a counter, but while a counter increments by 11, an accumulator increments by varying values.

    • Accumulators require three actions:

      1. Initialize the accumulator to 00.

      2. Alter the accumulator exactly once for every data set processed.

      3. Output the final accumulated value after processing ends.

    • Summary Reports: Reports containing only totals without individual detail data. Loops are used to process data, but detail information is skipped in the output.

  • Data Validation:

    • Defensive Programming: The practice of preparing for all possible errors before they occur.

    • Validation: Ensuring data falls within acceptable ranges (e.g., months between 11 and 1212).

    • GIGO (Garbage in, Garbage out): A principle stating that unvalidated or incorrect input will result in erroneous output.

    • Loops are used to reprompt users continuously until they provide valid data.

    • Limiting Reprompts: To avoid frustrating users, a program can maintain a count of reprompts (e.g., ATTEMPTS = 3). If the limit is reached, the program might "force" a data item by setting it to a specific default value.

  • Validating Data Type:

    • Programs use methods often referred to as "black boxes" to check data types.

    • Common methods include isNumeric(), isChar(), and isWhitespace().

    • Data can be accepted as strings and then converted to the correct type using built-in language methods after validation.

Comparing Selections and Loops

  • Selection Structure: The logical paths (True and False) eventually join together after the specific actions are completed.

  • Loop Structure: One of the logical branches returns to the same decision that controls the structure.

  • Efficient structured logic for reading records (like employee records) relies on loop structures that eventually return to the decision to check for more data, whereas inefficient logic might fail to bridge these paths correctly.