Sign in

Libre University uses your GitHub account. Signing in is only needed to sit a final test, so the score is kept on your profile.

Loops and invariants

1.[2p]

How many times does the body of for (let i = 3; i < 12; i += 2) run?

CorrectNot quite: 5

2.[3p]

What is a loop invariant?

Correct

The answer is: A claim about the state that holds before the loop, is preserved by every pass, and is strong enough at the end to give the wanted result

The answer is: A claim about the state that holds before the loop, is preserved by every pass, and is strong enough at the end to give the wanted result

The answer is: A claim about the state that holds before the loop, is preserved by every pass, and is strong enough at the end to give the wanted result

3.[2p]

Put the three parts of a loop in the order the machine reaches them for the first time.

  1. The update

  2. The initialisation

  3. The condition

Show the answer

c, a, b

4.[3p]

for (let x = 0; x < 1; x += 0.1) steps++; How many times does the body run?

CorrectNot quite: 11

5.[2p]

The Collatz loop has been checked by computer for every starting value below about 2.95×1020 without exception, which counts as a proof that it always terminates.

The answer is: False

Correct

6.[3p]

Which of these are reasons for the for (let i = 0; i < n; i++) convention?

Select all that apply

Correct
Correct
Correct

The answer is: The number of passes is n, readable off the header with no arithmetic, Two adjacent half open ranges join with no gap and no overlap, It matches array indices, where the first element is at 0 and the last at n - 1

7.[2p]

How many trial divisions does for (let d = 2; d * d <= n; d++) perform for n = 97?

CorrectNot quite: 8

8.[3p]

Match each term to what it means.

  • Invariant

  • Variant

  • Accumulator

  • Fencepost error

  • Infinite loop

  • a name declared outside the loop and updated inside it

  • a claim the body preserves on every pass

  • counting the gaps when you meant the boundaries

  • a whole number that strictly decreases and cannot go below zero

  • a condition that never becomes false because the state stops changing

Show the answer

Invariant: a claim the body preserves on every pass Variant: a whole number that strictly decreases and cannot go below zero Accumulator: a name declared outside the loop and updated inside it Fencepost error: counting the gaps when you meant the boundaries Infinite loop: a condition that never becomes false because the state stops changing

9.[2p]

A program neither crashes nor prints anything and never returns. What is the most likely cause?

Correct

The answer is: A loop whose state is not being changed, so its condition never becomes false

The answer is: A loop whose state is not being changed, so its condition never becomes false

The answer is: A loop whose state is not being changed, so its condition never becomes false