UNIHIVE

Study Hub UNIPORT MTH 280

MTH 280 · Introduction to Computer programming

Loops: for, while and repeat

Counting loops and condition loops, accumulators and counters, nested loops, break and continue, and tracing loops by hand.

Our notes

1 min read

Why loops

A loop repeats a block of statements, so 1,000 records need the same few lines as 3.

Counting loop: for

for i in range(1, 6):
    print(i)
prints 1 2 3 4 5. range(a, b) counts from a up to b - 1; range(1, 11, 2) gives 1, 3, 5, 7, 9; range(10, 0, -1) counts down 10 to 1.

Condition loop: while

Repeats while the condition is true; the condition is checked before each pass (it may run zero times).
n = 1
while n <= 100:
    n = n * 2
print(n)
Trace: 1, 2, 4, 8, 16, 32, 64, 128 → stops when n = 128 and prints 128.

Repeat-until (post-test loop)

Pascal's REPEAT … UNTIL and C's do … while check the condition after the body, so the body runs at least once. In Python: while True: … if condition: break.

Accumulators and counters

Sum and average of N numbers:
n = int(input("How many? "))
total = 0
for i in range(n):
    x = float(input("Number: "))
    total = total + x
print("Sum", total, "Average", total / n)
With n = 3 and inputs 4, 8, 6: total goes 4, 12, 18 → Sum 18.0 Average 6.0.

Counting passes:
passes = 0
for s in scores:
    if s >= 40:
        passes = passes + 1

Sentinel loop (stop at a special value):
total = 0
x = int(input())
while x != -1:
    total = total + x
    x = int(input())

Nested loops

A loop inside a loop: the inner loop runs completely for each pass of the outer.
for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end=" ")
    print()
prints a 3 × 3 multiplication table: 1 2 3 / 2 4 6 / 3 6 9. The inner print runs 3 × 3 = 9 times.

break and continue

  • break leaves the loop at once.
  • continue skips to the next pass.

Classic loop programs

  • Factorial: fact = 1; for i in range(1, n + 1): fact = fact * i. 5! = 120.
  • Fibonacci: a, b = 0, 1; repeat: print(a); a, b = b, a + b → 0 1 1 2 3 5 8 …
  • Sum of digits of 4,725: repeatedly add n % 10 and do n = n // 10 → 5 + 2 + 7 + 4 = 18.
  • Prime test: n is prime if no number from 2 to √n divides it.

Exams usually ask: write loops for sums, averages, factorials, tables, Fibonacci, primes; convert a for loop to a while loop; trace a loop and give the output or the number of passes.

Common mistake: an infinite loop: forgetting to change the loop variable inside a while loop (n never grows, so n <= 100 is always true). Also off-by-one errors with range (range(1, 10) stops at 9).

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All MTH 280 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.