You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers iteration (loops) as required by OCR J277 Section 2.3. Iteration means repeating a block of code. OCR requires you to know three types of loop: for loops (count-controlled), while loops (condition-controlled), and do...until loops (condition-controlled, post-test).
Iteration is the process of repeating a set of instructions either a fixed number of times or until a condition is met. Without iteration, you would have to write the same code many times over.
There are two main categories:
| Type | Description | OCR Loop Types |
|---|---|---|
| Count-controlled | Repeats a fixed number of times | for loop |
| Condition-controlled | Repeats until a condition changes | while loop, do...until loop |
The following flowchart shows the logic of a while loop (condition checked before each iteration):
flowchart TD
A([Start]) --> B{Condition\ntrue?}
B -- No --> E([End loop])
B -- Yes --> C["Execute loop\nbody"]
C --> D["Update\nvariable"]
D --> B
A for loop repeats a block of code a specific number of times. You know in advance how many iterations are needed.
OCR Pseudocode:
for i = 0 to 4
print("Hello " + str(i))
next i
This prints:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Python:
for i in range(5): # range(5) gives 0, 1, 2, 3, 4
print("Hello", i)
for variable = start to end
// code to repeat
next variable
start to end inclusive.for i = 1 to 10 runs 10 times (i = 1, 2, 3, ..., 10).for i = 0 to 9 also runs 10 times (i = 0, 1, 2, ..., 9).OCR Exam Tip: In OCR pseudocode,
for i = 0 to 4iterates 5 times (0, 1, 2, 3, 4) because both endpoints are inclusive. In Python,range(5)also gives 5 values (0 to 4) but the upper bound is exclusive. Be careful with this difference.
A while loop repeats as long as a condition is true. The condition is checked before each iteration, so the loop body might not execute at all.
OCR Pseudocode:
password = ""
while password != "secret"
password = input("Enter password: ")
endwhile
print("Access granted")
Python:
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted")
A do...until loop is similar to a while loop, but the condition is checked after each iteration. This means the loop body always executes at least once.
OCR Pseudocode:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.