Understand the idea
A loop invariant is a property that remains true at a defined point in every iteration. State initialisation, maintenance and what termination implies.
WORKED EXAMPLE
For summing [2,4,6], after k items total equals the sum of the first k items. At k=0 total=0; at k=1 total=2; k=2 total=6; k=3 total=12.
Watch it step by step
Step 1 of 4Initialise
At k=0, total=0: no items have been processed.
Choose Play to advance steps automatically.
Read or choose any step
- Initialise
At k=0, total=0: no items have been processed.
- Maintain 1
After item 2, k=1 and total=2.
- Maintain 2
After item 4, k=2 and total=6.
- Terminate
After item 6, k=3 and total=12.
TRY BEFORE CHECKING
Exercises with feedback
MAKE SOMETHING YOU CAN EXPLAIN
Your practical challenge
Explain initialisation, maintenance and termination for the example. Add assumptions about numeric inputs.
These ticks are your self-review. They do not automatically assess project quality. Ask an adult or partner to review what you can show.
Use the skill in a new situation
Adapt the reasoning to counting matching items.