Reading Algorithms

You may be asked to describe what happens in an algorithm or to specify the output.

Follow the variables through the loop.

score = 0
for i = 1 to 5 # this will run the loop with i taking the values 1 - 5
   score = score + 1
   print "Score is", score

The loop will simply run 5 times with i taking the values 1,2,3,4 and 5. As i does not feature in the loop, the score will simply increase by 1 each time. The output would be:

Score is 1
Score is 2
Score is 3
Score is 4
Score is 5

This algorithm is slightly different. Note i is added each time instead of 1.

score = 0
for i = 1 to 5 # this will run the loop with i taking the values 1 - 5
   score = score + i
   output "Score is", score

As i is added to score each time, score increases more quickly. Score will increase as follows:

  • 0 + 1 = 1
  • 1 + 2 = 3
  • 3 + 3 = 6
  • 6 + 4 = 10
  • 10 + 5 = 15
Score is 1
Score is 3
Score is 6
Score is 10
Score is 15
score = 0
for i = 1 to 5 # this will run the loop with i taking the values 1 - 5
   score = score + i
   if score > 5:
      output "Score is", score # score only prints now if it is greater than 5
Score is 6
Score is 10
Score is 15

Common mistakes: be careful to ensure that you note the full output including any text.

Try some sample questions – Algorithms

%d bloggers like this: