Back

Written Response Rehearsal: The Loop

Three problems · on paper · this is Written Response 2(a)

divider

Objective

This is one of your six Create Task points, rehearsed on somebody else's code. In May you will answer it about your own program, with only your Project Reference in front of you.

The Real Prompt
WRITTEN RESPONSE 2(a)
Identify the number of times the body of the
iteration statement will execute.
AND describe a condition or error that would
cause an infinite loop.

Notice the word and. Both halves or nothing — a correct count with no infinite-loop answer scores the same as a blank page.

These are in exam notation on purpose. Your own program is in C#, but the exam's multiple-choice questions use the reference sheet, and counting is counting. If the notation slows you down, that is the thing to fix before May.

Paper only. Do not run these.

divider

The Problems


Problem 1

countAbove
scores ← [88, 42, 95, 60, 71]
PROCEDURE countAbove(aList, limit)
{
found ← 0
i ← 1
REPEAT UNTIL(i > LENGTH(aList))
{
IF(aList[i] > limit)
{
found ← found + 1
}
i ← i + 1
}
RETURN(found)
}
DISPLAY(countAbove(scores, 65))
  1. How many times does the loop body execute?
  2. What does the program display? Be exact.
  3. Describe one change that would make this loop run forever, and say why it never stops.
  4. Now a harder one. Without changing the loop at all, describe a value of aList that makes the body execute zero times.

Problem 2

halve
PROCEDURE halve(n)
{
steps ← 0
left ← n
REPEAT UNTIL(left = 0)
{
steps ← steps + 1
left ← (left - (left MOD 2)) / 2
}
RETURN(steps)
}
  1. How many times does the body execute for each of these? halve(20), halve(7), halve(1), halve(0).
  2. One of those four is worth pausing on. Which, and why?
  3. Someone replaces left ← (left - (left MOD 2)) / 2 with left ← left / 2. The loop now runs forever. Explain precisely why — the answer is not "because it is wrong."

Problem 3

grid
PROCEDURE grid(n)
{
total ← 0
i ← 1
REPEAT UNTIL(i > n)
{
j ← 1
REPEAT UNTIL(j > n)
{
total ← total + 1
j ← j + 1
}
i ← i + 1
}
RETURN(total)
}
  1. How many times does the inner body execute for grid(3), grid(4), and grid(5)?
  2. There are two loops here. Written Response 2(a) asks about the first iteration statement. Which one is that, and how many times does its body execute for grid(4)?
  3. Someone moves j ← 1 so that it sits above the outer loop instead of inside it. What does grid(4) return now? Explain what happened.

Then: Your Own

Find the first loop inside a procedure in your own program. Write out an answer to Written Response 2(a) about it — both halves, in full sentences.

If you cannot find a loop inside one of your own procedures, that is the most useful thing this page will tell you. You have sessions left to fix it.

divider

Submit

All three problems answered, plus your own Written Response 2(a) in full sentences.

Worth 5 points, graded on completion.

Commence Challenge