☰ Contents · Computing

Repeating algorithms

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
17

Practical lesson: repeating algorithms

Textbook: pp. 43–44
GoalSolves one problem with three kinds of loop, builds a trace table and writes repeating algorithms for sums, products and values of a function.
New words
trace table: a table of the variable values after each step · kuzatuv jadvalimultiple: a number that a given number divides without remainder · karrali sonloop limit: the last value of the parameter or the condition for stopping · sikl chegarasistep: the amount by which the parameter changes at each iteration · qadam
Explanation

The same result can be obtained with all three kinds of loop. Let us compute 4! = 1 · 2 · 3 · 4. Parameter loop: P = 1; i from 1 to 4: P = P · i. While loop: P = 1, i = 1; while i ≤ 4: P = P · i, i = i + 1. Until loop: P = 1, i = 1; repeat: P = P · i, i = i + 1; until i > 4. P takes the values 1, 2, 6, 24 in turn, so the answer is 24. When writing a loop check three things: the start values, the body and the stopping condition. For a sum of multiples the parameter step can equal the multiple, or a condition (remainder 0) is tested in the body. In a table of function values x changes at each step and the formula is recalculated for every x.

Worked examples
Trace table (while loop, 4!): i = 1: P = 1; i = 2: P = 2; i = 3: P = 6; i = 4: P = 24; i = 5: the condition i ≤ 4 is false – the loop ends with P = 24. The parameter loop gives the same values of P.
The sum of multiples of 3 from 1 to 20: S = 0; i from 3 to 18 with step 3, S = S + i: 3, 9, 18, 30, 45, 63. Answer: 63. Calculating y = x³ – 2x for x = –2, –1, 0, 1, 2, 3 gives –4, 1, 0, –1, 4, 21.
Class activity

“Loop contest”: three teams write the same problem with different loops (parameter, while, until); the tables are compared.

Practice
1
Find the sum of the multiples of 4 from 1 to 20.
2
Calculate the product of even numbers in a loop: P = 2 · 4 · 6 (start with P = 1, i from 2 to 6 with step 2).
3
Find the value of y = x³ – 2x at x = –2.
4
Why does the body of an “until” loop run at least once?