Sequence, selection, iteration and string handling

Computer Science · Programming. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science topics

The idea

Every program is built from three constructs. Sequence means the statements run one after another in order. Selection means the program chooses a path: IF tests a condition, and CASE picks one of several branches from the value of a single variable.

Iteration means repeating statements in a loop. Use a FOR loop when the number of repeats is known. Use WHILE or REPEAT when the loop must continue until something happens.

Inside loops you often keep a running total or a count. Statements can also be nested, which means one IF or loop sits inside another. Strings have their own routines for length, parts of the string and changing case.

In simpler words

Every program uses three building blocks. Sequence runs steps in order. Selection chooses a path with IF or CASE. Iteration repeats steps in a loop. Use FOR when you know how many times. Use WHILE or REPEAT when you stop on a condition. Loops often keep a total or a count. String routines find length or take part of a word.

An everyday comparison

The two condition loops are like two ways into a cinema. WHILE is a guard who checks your ticket at the door, so you might never get in. REPEAT is a guard who checks it as you leave, so you always see the film at least once. The comparison stops working because loops can repeat many times, while you usually watch a film once.

Rules to remember

Common mistake

In SUBSTRING the second number is how many characters to take, not the end position. Also remember that a WHILE loop does not run at all if its condition is false at the start.

In the exam

Name the construct the question asks for and use correct keywords, such as REPEAT ... UNTIL. Initialise totals and counters to 0 before the loop, then write Total ← Total + Value inside it. State whether a loop is count-controlled, pre-condition or post-condition, and justify the choice. For SUBSTRING, write the start position and number of characters. Indent nested statements clearly.

Worked example

What is output by this algorithm?
Total ← 0
FOR i ← 1 TO 5
    IF MOD(i, 2) = 1
      THEN
        Total ← Total + i
    ENDIF
NEXT i
OUTPUT Total

  1. The loop runs with i = 1, 2, 3, 4, 5.
  2. MOD(i, 2) = 1 is true only for the odd values 1, 3 and 5.
  3. Only those values are added: Total = 0 + 1 + 3 + 5 = 9.

Answer: 9

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Variables, data types and operatorsProcedures, functions and maintainable programs →Take a Computer Science test