Zum Inhalt springen

English:Iteration and Loops

Aus MOOCsWiki Staging

Iteration and Loops



Introduction

Iteration means repeating a process. In computer programming, a loop repeats a block of instructions so that you do not have to write the same instructions again and again. Each single repetition is called an iteration. Loops are part of control flow, because they help a program decide what to do next and when to repeat an action.

You already use repetition in everyday life. You might take ten steps, check several answers in a worksheet, or keep stirring until a mixture is smooth. A programmer turns this idea into a precise rule: repeat an action a certain number of times, repeat it for every item, or repeat it while a condition is true.

Fehler beim Erstellen des Vorschaubildes:

This image gives an overview of common programming loop patterns. As you work through the course, look for three important ideas: what repeats, what controls the repetition, and what makes the loop stop.

The Code.org video above introduces repeat blocks. Block-based programming is a useful starting point because you can see the repeated instructions inside the loop.


Learning Goals

By the end of this aiMOOC, you should be able to explain iteration, choose an appropriate loop, trace a loop step by step, predict its output, identify common loop errors, and design a short algorithm that uses repetition efficiently.

You will work mainly with language-independent pseudocode. Real programming languages use different symbols and keywords, but the logical ideas are similar.


Why Programmers Use Loops

Imagine that a program must display the word "Hello" twenty times. Writing the same output command twenty times would be long, repetitive, and difficult to edit. A loop can express the same idea with one repeated block.

Loops are useful when a program needs to:

  1. Repeat an action: Move a game character several steps.
  2. Process items: Check every name in a class list.
  3. Simulate change: Update a value once per turn.
  4. Validate input: Keep asking until the user enters an acceptable answer.
  5. Build patterns: Draw repeated shapes, rows, or symbols.

A loop can make an algorithm shorter and easier to change. However, a loop must also be controlled carefully. If its stopping rule is wrong, the program can repeat too few times, too many times, or forever.


The Anatomy of a Loop

Most loops can be understood by looking for four parts.

  1. Initialization: A starting value is prepared, such as setting a counter to zero.
  2. Condition: A test decides whether another repetition should happen.
  3. Loop body: The instructions inside the loop are carried out.
  4. Update: A value changes so that the loop can make progress.

Consider this pseudocode:

set counter to 1
while counter is at most 4
    display counter
    add 1 to counter
end while

The starting value is 1. The condition checks whether the counter is at most 4. The body displays the counter. The update adds 1. The output is 1, 2, 3, 4.

A useful question is: What changes after each iteration? If nothing relevant changes, a condition-controlled loop may never reach its stopping point.


Count-Controlled Iteration: For Loops

A for loop is often used when the program knows the number of repetitions or can step through a planned range of values. A loop counter changes automatically or according to a rule.

for each number from 1 through 5
    display number
end for

This loop has five iterations. The loop variable takes the values 1, 2, 3, 4, and 5.

A for-loop flowchart helps you see that the program enters the loop, performs the body for each allowed value, and then leaves the loop after the sequence is complete.

This unplugged Code.org activity shows how a changing loop value can control repeated actions without requiring a computer.


Choosing a Start, Stop, and Step

Many count-controlled loops can be described with a start value, a stopping point, and a step. For example, a loop might count 2, 4, 6, 8, 10 by starting at 2 and adding 2 each time.

When you trace a loop, write down every value the counter actually takes. This helps you avoid an off-by-one error, where a loop runs one time too many or one time too few.

For example, compare these two intentions:

Intention A: display 1 through 5
Values: 1, 2, 3, 4, 5

Intention B: display values smaller than 5
Values: 1, 2, 3, 4

The difference is whether 5 is included. Small boundary differences can change the result.


Condition-Controlled Iteration: While Loops

A while loop repeats as long as a condition is true. It is especially useful when you do not know in advance exactly how many repetitions will be needed.

ask for a password
while the password is incorrect
    ask for a password again
end while
display "Access granted"

The loop might run zero times if the first password is correct, or it might run several times if the user keeps entering an incorrect password.

The decision shape in the flowchart represents the condition. If the condition allows another repetition, the program returns to the loop body. If not, the program continues after the loop.

The Khan Academy video above demonstrates how a while loop repeats code based on a condition.


= Avoiding Infinite Loops

An infinite loop continues without reaching its normal stopping point. This often happens when the condition always stays true or when a variable that should change is never updated.

set score to 0
while score is less than 10
    display score
end while

This is a problem because score never changes. The condition remains true forever. One repair is to change the score inside the loop:

set score to 0
while score is less than 10
    display score
    add 1 to score
end while

Before running a while loop, ask yourself two questions: What must eventually make the condition false? and Does the loop actually move toward that state?


For Loop or While Loop?

Both loop types repeat instructions, but they are controlled in different ways.

Situation Useful loop choice Reason
Repeat a dance move eight times For loop The number of repetitions is known.
Print every item in a fixed list For loop The program can visit each item in turn.
Keep asking until an answer is valid While loop The number of attempts is not known beforehand.
Continue a game while the player has lives While loop Repetition depends on a changing condition.

These are practical guidelines, not absolute rules. Many problems can be solved in more than one way. The best choice is usually the one that makes the logic easiest to understand and test.


Comparing the Same Task with Two Loops

The two flowcharts below show the same general problem—finding the average of five user-entered numbers—implemented using different loop structures.

Datei:02. Average of 5 Numbers (using while loop) - Start.svg

Study the diagrams and notice that the for-loop version makes the planned repetition count clear, while the while-loop version makes the condition and update especially visible. Comparing equivalent algorithms is a good way to understand how loop structures differ.


Nested Loops

A nested loop is a loop inside another loop. The inner loop completes its repetitions for each single repetition of the outer loop.

Imagine creating a grid with three rows and four columns. The outer loop can represent the rows, and the inner loop can represent the columns.

repeat for each row
    repeat for each column
        place one tile
    end repeat
end repeat

If there are 3 rows and 4 columns, the instruction "place one tile" runs 12 times because each of the 3 outer iterations contains 4 inner iterations.

Nested loops are useful for grids, tables, pixel patterns, board games, repeated geometric designs, and comparisons between groups of items. They can also cause many operations, so programmers should understand how the number of repetitions grows.


Tracing a Loop

Tracing means following an algorithm one step at a time and recording how its values change. A trace table can reveal errors before you even run the program.

Consider:

set total to 0
for each number from 1 through 4
    add number to total
end for
display total

A trace table could look like this:

Iteration Current number Total after the addition
First 1 1
Second 2 3
Third 3 6
Fourth 4 10

The final output is 10. Tracing shows not only the final result but also how the program reaches it.


Common Loop Errors and Debugging

Debugging is the process of finding and correcting problems in an algorithm or program. Loop bugs are often caused by boundaries, conditions, or updates.

  1. Off-by-one error: The loop starts or stops at the wrong boundary.
  2. Infinite loop: The stopping condition is never reached.
  3. Initialization: A counter or total begins with an unsuitable value.
  4. Update: A value changes in the wrong direction or does not change at all.
  5. Nesting: An inner loop is placed incorrectly or repeats more often than expected.

A good debugging method is to use a very small test case. If a loop should process one hundred values, first test it with three. Predict the result, trace the values, run the program, and compare the actual result with your prediction.

This Khan Academy video focuses on tracing loop execution step by step, which is one of the most useful debugging skills for beginners.


Loops in Creative and Real-World Programs

Loops appear in many kinds of software. A drawing program can repeat a move-and-turn pattern to create polygons. A game can update positions every turn. A data program can examine each item in a collection. A sensor program can keep checking a reading. A music program can repeat rhythmic patterns.

In this Code.org video, a software engineer demonstrates how loops can be used in app programming. As you watch, focus on how repetition reduces duplicated code.

A strong programmer does more than make a loop run. You should also be able to explain why the loop is needed, what controls it, how it stops, and how you know it produces the intended result.


Interactive Tasks


Quiz: Test Your Knowledge

What is one iteration? (One repetition of a process) (!A type of computer screen) (!A stored password) (!A programming language)




Why are loops useful in programs? (They repeat instructions efficiently) (!They remove all conditions) (!They turn code into pictures) (!They prevent every error)




Which loop is usually suitable when the repetition count is known? (A for loop) (!A while loop only) (!A comment block) (!An input statement)




Which loop is usually suitable when repetition depends on a changing condition? (A while loop) (!A print statement) (!A variable name) (!A fixed comment)




What should normally change in a condition-controlled loop? (A value related to the stopping condition) (!The computer keyboard) (!The file name) (!The screen size)




What is an infinite loop? (A loop that does not reach its normal stopping point) (!A loop that runs exactly twice) (!A loop with no body) (!A loop used only for pictures)




What is a nested loop? (A loop placed inside another loop) (!A loop with no condition) (!A loop that cannot repeat) (!A loop written as a comment)




What does tracing a loop help you do? (Follow changing values step by step) (!Delete every variable) (!Increase internet speed) (!Choose a computer password)




What is an off-by-one error? (A loop boundary causes one extra or missing repetition) (!A computer has one extra key) (!A variable has no name) (!A program contains only one line)




In a grid made with nested loops, what might the outer loop represent? (The rows) (!The power button) (!The file extension) (!The password)





Memory Game

Iteration One repetition of a process or loop
Counter A variable that keeps track of repetitions
Condition A test that can control whether repetition continues
Body The instructions that are repeated by a loop
Update A change that helps a loop progress
Nested loop A loop located inside another loop
Trace table A record of how values change step by step
Infinite loop Repetition that does not reach its normal stopping point





Drag and Drop

Match the correct terms. Topic
Count-controlled loop Repeats according to a planned number of iterations
Condition-controlled loop Repeats while a test allows it to continue
Loop body Contains the instructions that repeat
Loop counter Tracks progress through repeated steps
Debugging Finds and corrects mistakes in an algorithm




Match each programming idea with the explanation that best describes it.


Crossword Puzzle

Iteration What word means one repetition of a process?
Counter What variable can track how many repetitions have occurred?
Condition What test can decide whether a while loop continues?
Nested What kind of loop is placed inside another loop?
Infinite What word describes a loop that does not normally stop?
Trace What word means to follow an algorithm step by step?





LearningApps


Cloze Text

Complete the text.

In programming, repeating a process is called

. A loop repeats a block of instructions called the

. A for loop is often useful when the number of repetitions is

. A while loop continues according to a

. A variable that tracks repetitions can be called a

. A condition-controlled loop should make progress toward its

state. A loop that never reaches its normal stopping point is called

. Following changing values step by step is known as

. A loop inside another loop is called a

loop.




Open-Ended Tasks


Easy

  1. Loop Hunt: Find three examples of repetition in everyday life and explain what repeats, what controls the repetition, and what makes it stop.
  2. Human Robot: Write clear instructions for a partner to repeat a simple classroom action exactly five times, then test whether your instructions are unambiguous.
  3. Pattern Maker: Design a small paper or digital pattern that could be produced by repeating one action, and describe the loop that would create it.
  4. Trace a Counter: Create a trace table for a loop that counts from 2 to 10 in steps of 2, then explain how you know when it stops.


Standard

  1. Loop Storyboard: Draw a six-panel storyboard that explains initialization, condition, body, update, stopping, and output using one consistent example.
  2. Input Validator: Write pseudocode for a program that keeps asking for a number until the user enters a value from 1 through 10, then test it with at least three input sequences.
  3. For and While Comparison: Solve the same repeated task once with a for loop and once with a while loop, then compare which version is clearer and why.
  4. Interview a Programmer: Interview a programmer, teacher, or advanced student about where loops appear in real projects, then summarize two examples and one debugging tip.


Advanced

  1. Nested Grid Project: Create a program or detailed pseudocode plan that builds a rectangular grid with nested loops, then explain how changing the row and column counts changes the total work.
  2. Loop Debugging Lab: Write three faulty loops that demonstrate an off-by-one error, a missing update, and a wrong-direction update, then repair each one and justify the fix.
  3. Efficiency Investigation: Compare a repeated task written with duplicated instructions and with a loop, then analyze readability, ease of editing, and the number of repeated operations.
  4. Iteration Video Tutorial: Produce a short teaching video that demonstrates a for loop, a while loop, and a nested loop using your own examples, including a trace or visual explanation for each.



Learning Assessment

  1. Loop Selection Assessment: Given four programming situations, choose a suitable loop for each and justify your choices using the information known before the loop starts.
  2. Trace and Predict: Trace an unfamiliar loop with a table, predict its output, and explain how each update changes the next condition check.
  3. Debug and Repair: Diagnose a loop that repeats forever, identify the exact cause, repair it, and explain why the revised version must make progress toward stopping.
  4. Boundary Reasoning: Compare two loops with slightly different start or stop conditions and explain how the boundary change affects the number of iterations and the output.
  5. Nested Loop Transfer: Design nested-loop pseudocode for a new grid or pattern problem, then calculate how many times the inner action runs and justify your calculation.
  6. Algorithm Redesign: Replace a block of duplicated instructions with a loop, then evaluate whether the redesigned algorithm is clearer, easier to change, and equally correct.




Evidence of Learning

  1. Knowledge: You can explain iteration, loop bodies, counters, conditions, updates, for loops, while loops, nested loops, and infinite loops in your own words.
  2. Skills: You can trace repeated execution, predict output, choose a loop type, identify boundaries, and debug common loop errors.
  3. Products: You can produce pseudocode, trace tables, diagrams, tested programs, patterns, or teaching media that use loops correctly.
  4. Transfer: You can recognize repetition in a new problem, design an appropriate stopping rule, and justify how your loop makes progress and produces the intended result.




OERs on the Topic



Linked Learning Areas

Iteration and loops connect Computer science with mathematical patterns, logical reasoning, problem solving, game design, robotics, data processing, and digital creativity. Understanding repetition prepares you for more advanced work with collections, simulations, algorithms, and software design.


aiMOOC Projects