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.

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.

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