Back to Challenge Set 20

Pseudocode Challenge: Counting the Steps

Difficulty  

divider

Objective

Three loops in exam notation — Activity 2.12. For each one, count how many times the marked statement runs, for n = 8, then 16, then 32.

Do not run these. Count them. The written response on the exam asks this about your own program, with no computer in the room either.


Reference Card

What you are allowed to use
REPEAT n TIMES { } runs the block n times;
NO loop counter is provided
REPEAT UNTIL(condition) repeats UNTIL it becomes true;
keep your own counter if you need one
a ← expression assign the result to a
a MOD b remainder: 17 MOD 5 is 2
a / b ORDINARY division: 17 / 5 is 3.4
There is no for loop on the reference sheet.

The Problems

Problem 1 — Count

How many times does <one step> run, for n = 8, 16, and 32?

Problem 1
i ← 1
REPEAT UNTIL(i > n)
{
j ← 1
REPEAT UNTIL(j > n)
{
<one step>
j ← j + 1
}
i ← i + 1
}

Then answer this: the input doubled twice. What happened to the step count each time?

Problem 2 — Count

What is displayed, for n = 8, 16, and 32?

Problem 2
left ← n
steps ← 0
REPEAT UNTIL(left < 1)
{
steps ← steps + 1
left ← (left - (left MOD 2)) / 2
}
DISPLAY(steps)

Then answer this: you have seen these three numbers before. Which algorithm from this unit do they belong to, and why is that not a coincidence?

Problem 3 — Count

This looks like Problem 1. How many times does <one step> run, for n = 8, 16, and 32?

Problem 3
i ← 1
REPEAT UNTIL(i > n)
{
j ← 1
REPEAT UNTIL(j > 3)
{
<one step>
j ← j + 1
}
i ← i + 1
}

Then answer this: Problems 1 and 3 are both a loop inside a loop, and only one of them grows like n × n. Say in one sentence what in the code decides that.

And this: at n = 2, Problem 3 does more steps than Problem 1. At n = 32 it does far fewer. Work out both, and explain why comparing two algorithms at one small size can mislead you.


Submit

  • Your nine step counts, in a table with a row per problem and a column per value of n
  • The two n = 2 counts
  • Your answers to the Then and And questions

This is graded on completion, not accuracy. Show your working — a wrong answer with visible reasoning is worth more to both of us than a right one with none.

Commence Challenge