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
whileloop’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:
The loop control variable must be initialized before entering the loop.
The loop control variable must be tested in the loop's condition.
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 .
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
whileloop that outputs "Hello" exactly 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
whileloop 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:
Initialize: Provide a starting value for the variable that will control the loop.
Test: Compare the loop control variable to determine whether the loop body should execute or terminate.
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 ().
Avoiding Common Loop Mistakes
Neglecting to initialize the loop control variable:
If a variable like
nameis not initialized (e.g., aget namestatement 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., labels) with invalid data.
Neglecting to alter the loop control variable:
Removing the instruction to update the variable (e.g., removing a
get nameinstruction 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 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 discount for every item by repeating the math inside a loop 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
forstatement (orforloop) is a specialized definite loop structure.It provides three actions in a single structure: initialization, evaluation (testing), and alteration.
A
forloop example logic:for count = 0 to 3 step 1 output "Hello" endfor.It initializes
countto .It checks
countagainst the limit value of .If the evaluation is true, it executes the body (printing "Hello").
It increases
countby 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 .
Programmers specify a step value when the loop control variable needs to change by a value other than .
Pretest vs. Posttest Loops
Pretest Loop:
The loop control variable is tested before every iteration.
Both
whileandforloops are categorized as pretest loops.
Posttest Loop:
The loop control variable is tested after each iteration.
The
do...whilestructure 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 , an accumulator increments by varying values.
Accumulators require three actions:
Initialize the accumulator to .
Alter the accumulator exactly once for every data set processed.
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 and ).
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(), andisWhitespace().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.