Lessons 16–17 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
16
Repeating algorithms
Textbook: pp. 40–42
GoalExplains a repeating algorithm, loop body and iteration; tells the three kinds of loop apart (while, until, parameter) and calculates a sum and a product in a loop.
New words
repeating algorithm: part of the steps is carried out several times · takrorlanuvchi algoritmloop body: the group of instructions that is repeated · sikl tanasiiteration: one pass through the loop body · iteratsiyaloop parameter: a counter that changes by a fixed step from its start value to its end value · sikl parametri
Explanation
In a repeating algorithm a group of instructions is carried out again and again until a condition is met or a fixed number of times. The repeated part is the loop body, and each execution of it is an iteration. There are three kinds of loop. “While” (the condition is checked first): the body runs if the condition is true; if the condition is false from the start, the body never runs. “Until” (the condition is checked after): the body runs first, then the condition is checked and the loop stops when it is true; the body runs at least once. A parameter loop: the parameter changes from A to B, the number of repetitions is B – A + 1 and is known in advance. Repeating algorithms contain instructions like S = S + i (a sum) and P = P · i (a product); the start value is S = 0 for a sum and P = 1 for a product because these do not change the result.
Worked examples
While loop: S = 0; while S < 20, S = S + 4. Steps: S = 4, 8, 12, 16, 20; when S = 20 the condition is false and the loop stops. The body ran 5 times.
The sum of odd numbers 1 + 3 + 5 + 7 + 9: S = 0, i = 1. i = 1: S = 1; i = 3: S = 4; i = 5: S = 9; i = 7: S = 16; i = 9: S = 25. At each step 2 is added to i. Answer: 25.
Class activity
“Counting steps”: the class says S = S + i aloud: one student says i, the next says the new S; the trace table is filled in on the board.
Practice
1
What are a loop body and an iteration?
The loop body is the repeated group of instructions; an iteration is one execution of it.
2
S = 0, i = 1; while i ≤ 4: S = S + i, i = i + 1. What is the final S?
10
3
If the parameter changes from 3 to 9, how many times does the loop repeat?
7
4
Why do we start with S = 0 for a sum and P = 1 for a product?
Adding 0 and multiplying by 1 do not change the result.