Algorithm Analysis course guide
Week 03

Week 03 — Repeating Work: Loops and a Step Counter

This is supporting reference material. Return to Week 03 lesson →

About this reference

Detailed teacher notes, original lesson link, analysis prompts, model solutions, and added timed-practice material.

Find a topic in this reference

The big question

How do I make the computer repeat work, and how do I count that work?

A five-line program can perform thousands of operations. Decisions and loops let us investigate how work changes with input. Trace tiny cases first; formulas should summarize an understood pattern.

Trace if, for, and while; explain range endpoints; maintain an accumulator; and count a specified operation. Distinguish visits, accepted values, and inner-body executions: their counts can differ.

Retrieval with answers

QuestionAnswer
Old total is 7. What does total = total + 3 do?Calculate 7 + 3, then store 10.
What is 17 % 5?2, since 17 = 3 × 5 + 2.
What is 17 // 5?3, the number of complete groups of five.
Does = test equality?No. = assigns; == compares values.

If uncertain, revisit Week 2 assignment. Distinguish a value before an iteration from its value afterward.

Decisions: one selected path

An if condition produces True or False. Its indented block runs only when the condition is true. In an if / elif / else chain, Python selects the first true branch, or the final else if none is true. It does not execute every branch whose condition might be true independently.

For the lesson's weather example, “hot” means temperature > 30, “warm” means the remaining cases with temperature > 15, and “cool” covers everything else. Therefore 31 is hot, 30 is warm, and 15 is cool. Exact boundary values reveal whether you intended > or >=.

and requires both conditions; or needs at least one; not reverses a Boolean result. A multiple of both three and five satisfies number % 3 == 0 and number % 5 == 0. In FizzBuzz, check this combined case before the single-multiple cases, or 15 will enter the first single case too early.

Türkçe açıklama: Koşul sırası, sorunun çözümünün bir parçasıdır. if ile başlayan tek zincirde ilk doğru dal seçilince aşağıdaki elif dalları denenmez. “Her koşulu ayrı ayrı kontrol et” ile “uygun tek sınıfı seç” aynı algoritma değildir.

Repetition: define exactly which values are visited

range(5) visits 0, 1, 2, 3, 4. range(1, 6) visits 1, 2, 3, 4, 5. Both contain five values. The stop value is excluded, which lets range(n) repeat exactly n times for a nonnegative integer n. range(10, 0, -1) visits ten down to one; the negative step moves toward the excluded zero.

A for loop visits a supplied sequence. A while loop repeats while a condition is true. With while, identify what changes and why the condition must eventually become false. For example, subtracting one from a positive countdown moves it toward zero. Forgetting that update can produce an infinite loop.

Türkçe açıklama: range(1, n) yazınca n dahil değildir. Son değeri ezberlemek yerine üç küçük değer yaz: n = 4 için 1, 2, 3 gelir. Amaç 1'den 4'e kadar toplamaksa durma sınırı 5 olmalıdır.

Worked example 1: an accumulator and its counter

Add the integers from one through four. total stores the mathematical result so far. steps counts executions of the addition line; it does not count every operation performed by Python.

python
n = 4
total = 0
steps = 0
for value in range(1, n + 1):
    total = total + value
    steps = steps + 1
print(total, steps)
output
10 4
Iterationvaluetotal beforeAdditiontotal aftersteps after
1100 + 111
2211 + 232
3333 + 363
4466 + 4104

The initialization total = 0 runs before the loop. Moving it inside would erase the previous sum every iteration, leaving only the last value, four. The counter follows the same pattern: initialize once, update once per counted event.

For general nonnegative n, the selected addition executes n times. The resulting sum is n × (n + 1) / 2: at four, 4 × 5 / 2 = 10. These are different quantities. At 100, the answer is 5050 but the addition count is 100.

Türkçe açıklama: Sonucun büyüklüğü, işlemin kaç kez yapıldığı değildir. Para toplarken kutudaki toplam tutar ile kutuya kaç kez para koyduğun ayrı sayılardır. total birinciyi, steps ikinciyi izler.

Worked example 2: count a grid row by row

For each of three rows, visit each of three columns. The inner loop restarts for every outer iteration.

python
n = 3
steps = 0
for row in range(n):
    for column in range(n):
        steps = steps + 1
        print(row, column, steps)
print("Total:", steps)
output
0 0 1
0 1 2
0 2 3
1 0 4
1 1 5
1 2 6
2 0 7
2 1 8
2 2 9
Total: 9
Outer valueInner valuesWork in this rowAccumulated work
00, 1, 233
10, 1, 236
20, 1, 239

There are n rows and n visits per row, so the body executes n × n = n² times. Doubling n from three to six changes nine visits to 36: 36 / 9 = 4. Both dimensions doubled.

Two nested loops do not automatically mean n². If each row contains only two visits, the total is 2n. If row lengths differ, add their lengths. Always inspect the actual bounds.

Türkçe açıklama: İç içe döngüyü bir dikdörtgen gibi düşünmek, yalnızca her satır aynı uzunluktaysa doğrudur. İç sınır dış değişkene bağlıysa önce satırların uzunluklarını yaz; çarpım formülünü otomatik uygulama.

Halving: count reductions precisely

The integer-halving loop applies floor division until at most one remains. Trace actual updates rather than substituting an approximate search estimate.

python
remaining = 1000
reductions = 0
while remaining > 1:
    remaining = remaining // 2
    reductions = reductions + 1
    print(reductions, remaining)
print("Reductions:", reductions)
output
1 500
2 250
3 125
4 62
5 31
6 15
7 7
8 3
9 1
Reductions: 9

For starting sizes 1000, 10 000, 100 000 and 1 000 000, the counts are 9, 13, 16 and 19. Odd values round downward: 125 // 2 is 62. This program counts size reductions; it does not inspect a target, maintain a search interval or perform a final candidate comparison. Therefore its exact counts are not the exact guessing-game counts from Week 1. The shared idea is slow growth under repeated halving.

Türkçe açıklama: “Yaklaşık yarıya indirme” fikri doğru olsa da sayaç, yazdığın kodun olaylarını sayar. Son adayın kontrolü bu döngüde yoktur. Arama adımı ile tamsayı bölme adımını aynı saymak bir eksik veya bir fazla sonuca götürebilir.

Three practice problems with complete solutions

Practice 1 — visits and accepted values

Inspect every integer from one through six and count the even values. How many values are inspected, and how many pass the test?

Solution 1

python
n = 6
visited = 0
even_count = 0
for value in range(1, n + 1):
    visited = visited + 1
    if value % 2 == 0:
        even_count = even_count + 1
print(visited, even_count)
output
6 3

The visited values are 1, 2, 3, 4, 5, 6. The accepted values are 2, 4, 6. Thus six tests produce three successes. At n = 5, the counts become five and two. Türkçe: Koşul yanlış olduğunda o değer yine incelenmiştir; yalnızca başarı sayacı artmaz.

Practice 2 — stopping and skipping

First, test positive integers in order until finding one whose square exceeds 1000. How many tests occur? Second, sum one through 20 while skipping multiples of three. Find the sum, skipped count, and total visits.

Solution 2

31² = 961 is too small and 32² = 1024 exceeds 1000. Testing from one finds 32 after 32 tests; a break then ends the loop. A counter placed before the condition includes that successful final test.

The full sum is 20 × 21 / 2 = 210. Skipped numbers are 3, 6, 9, 12, 15, 18, totaling 3 × (1 + 2 + 3 + 4 + 5 + 6) = 3 × 21 = 63. The desired sum is 210 − 63 = 147, with six skips and 20 visits. continue skips the remaining body for one iteration; it does not terminate the loop. Türkçe: break aramayı bitirir, continue sadece mevcut adayın kalan işlemlerini atlar.

Practice 3 — unequal row lengths

For i from one through n, let j run from i through 2i, including both endpoints. Count the inner-body executions for n = 3, then write a general expression. This follows the lesson's Chapter 2 problem 2-35.

Solution 3

ij valuesRow count
11, 22
22, 3, 43
33, 4, 5, 64

An inclusive interval from i to 2i contains 2i − i + 1 = i + 1 values. Total work is 2 + 3 + ... + (n + 1) = n(n + 1)/2 + n = (n² + 3n)/2. At three, (9 + 9)/2 = 9. Python needs range(i, 2 * i + 1) to include 2i. Türkçe: Sondaki +1, iki uç dahil olduğundan gelir; uzunluk hesabında en sık kaybolan adımdır.

The chapter connections, without rushing

Problem 2-32 alternates squares: at five, 1 − 4 + 9 − 16 + 25 = 15 = 5 × 6 / 2. Pairing adjacent terms explains the cancellation; testing examples alone is evidence, not a proof for every input. For even k, the result is −k(k + 1)/2; for odd k, it is positive.

To see why, take an odd number a followed by a + 1. Their square difference is a² − (a + 1)² = −2a − 1 = −(a + (a + 1)). For even k, pairing every term therefore gives the negative sum from one through k. For odd k, the first k − 1 terms give −(k − 1)k/2; adding the last square gives k² − (k − 1)k/2 = (2k² − k² + k)/2 = k(k + 1)/2.

Problem 2-34 counts gifts. Day d gives d(d + 1)/2 gifts, so four days give 1 + 3 + 6 + 10 = 20. The cumulative formula is n(n + 1)(n + 2)/6. A loop adding the daily formula runs once per day: its addition count is n, even though the gift total grows like a cubic expression. State what you are counting before discussing growth.

Türkçe açıklama: İşaretli karelerde iki komşu terimi birlikte açınca büyük kareler birbirini götürür; tek sayıda terim varsa son kareyi ayrıca ekleriz. Hediyelerde ise toplam hediye sayısı ile günlük toplamı hesaplayan kodun işlem sayısı ayrıdır. Formülü kullanmak, her hediyeyi tek tek ziyaret etmek anlamına gelmez.

Misconceptions, glossary and repair

MisconceptionCorrection
Every nested loop has square growthCheck inner bounds and add row counts
Resetting the accumulator each round is harmlessIt erases previous work
A counter measures all running timeIt measures the event where you increment it
Testing many values proves a formulaA general argument must cover all allowed values
EnglishTürkçeMeaning
ConditionKoşulA true-or-false test
IterationYinelemeOne visit through a loop
AccumulatorBiriktiriciA value storing the running result
CounterSayaçA value recording events
Loop bodyDöngü gövdesiThe repeated indented instructions
TerminationSonlanmaReaching a condition that ends the process

For readiness, explain why a four-by-four grid makes 16 visits and why five even numbers among ten still require ten inspections. Explain where total = 0 belongs. Answers: four rows each contain four visits; every candidate needs a test; initialization belongs before accumulation begins.

If uncertain, use n = 3, write each visited value, and mark the counted line before increasing the input. Week 4 applies these counters to stored lists, scans, searches and pair comparisons.

Count visits separately from the total

A loop repeats instructions. A counter records how many times something happens. A running total adds up values; this is also called an accumulator. The count and the total can be different even in the same loop.

Draw or trace. For numbers 1, 2, 3, 4, write one row per visit with the current number, running sum and visit count.

Predict before checking. Will the sum and visit count end equal? What changes if the increase to the counter is placed inside an even-number test?

Worked reasoning

The running totals are 1, 3, 6, 10. The visit counts are 1, 2, 3, 4. Only two numbers are even, but the loop still visits all four. Before using a counter, say exactly what it counts. Putting it inside the even-number test counts matches, not all visits.

python
total = visits = matches = 0
for number in range(1, 5):
    visits += 1
    total += number
    if number % 2 == 0:
        matches += 1
assert (total, visits, matches) == (10, 4, 2)
print(total, visits, matches)

Change one thing. Use an empty range and then a range containing only odd numbers. Explain the difference between no visits and visits with no matches.

Türkçe: Sayaç hangi olayın kaç kez olduğunu ölçer. Eşleşme sayısı, ziyaret sayısı ve toplam değer birbirinin yerine kullanılamaz.

Additional analysis laboratory

This week is where students often start saying "the loop runs n times" too quickly. Make them name the values visited by the loop before they name n.

Loop descriptionValues visitedCount
range(5)0, 1, 2, 3, 45
range(2, 7)2, 3, 4, 5, 65
range(1, 8, 2)1, 3, 5, 74
while value halves from 32 until 132, 16, 8, 4, 2five tests before reaching 1 if the loop stops after the update

Extra exam-style prompt: A loop processes rows of lengths 2, 4, and 6. Is the total work 3, 6, 12, or something else?

Solution: It is 2 + 4 + 6 = 12 item visits. The outer loop has three rows, but the inner work depends on row length. If row lengths follow 2, 4, ..., 2n, the total is 2(1 + 2 + ... + n) = n(n + 1), which grows quadratically.

Turkce: Dongu kelimesini gormek yetmez. Hangi degerler ziyaret ediliyor? Ic dongu her satirda kac kez calisiyor? Once bu listeyi yaz, sonra formulu sec.

Other reference chapters