Paper 2: Pseudocode step by step (arrays, functions, procedures)

Paper 2: Pseudocode step by step (arrays, functions, procedures)

Strings: the built-in functions and four patterns

Strings AS Level 16 min read

On this page
  1. What you need to be able to do
  2. Why strings come before arrays
  3. The built-in functions
  4. The string patterns
  5. Worked example: initials
  6. Practice: three levels
  7. Mistakes that lose marks
  8. Can I do this?

What you need to be able to do

Syllabus 10.1, 11.1 (Paper 2)
  • 11.1Use the built-in string functions: LENGTH, MID, LEFT, RIGHT, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR.
  • 11.1Join strings with & and compare characters.
  • 9.2Go through a string one character at a time and build a new string from it.

You need: the toolkit (FOR loops, IF, ←).

Why strings come before arrays

About half of the long Paper 2 questions store strings in their arrays: names, passwords, product codes, lines of a file. So the question “find the customers whose code starts with "LHR"” is an array question and a string question. And a string is already a lot like an array: a row of characters, each at a position numbered from 1.

index12345678
Word'C''O''M''P''U''T''E''R'
The string "COMPUTER": 8 characters at positions 1 to 8. MID(Word, 3, 1) is the character at position 3: 'M'.
Two things to keep apart, here and with arrays: the position (3) and the character stored there ('M').

The built-in functions

Every Paper 2 has an appendix listing these functions, so you don't have to memorise the exact wording. What you do have to know is what each one gives back and how to use it in a line of code.

FunctionGives backExampleResult
LENGTH(S)how many characters (INTEGER)LENGTH("Lahore")6
LEFT(S, n)the first n charactersLEFT("Lahore", 3)"Lah"
RIGHT(S, n)the last n charactersRIGHT("Lahore", 3)"ore"
MID(S, start, n)n characters starting at position startMID("Lahore", 2, 3)"aho"
TO_UPPER(S) / TO_LOWER(S)the string in capitals / small lettersTO_UPPER("Ali 7")"ALI 7"
UCASE(c) / LCASE(c)one CHAR in capitals / small lettersUCASE('a')'A'
NUM_TO_STR(x)the number as a STRINGNUM_TO_STR(42)"42"
STR_TO_NUM(S)the string as a numberSTR_TO_NUM("17")17
IS_NUM(S)TRUE if S is a valid numberIS_NUM("12a")FALSE
ASC(c) / CHR(n)the character code / the character for a codeASC('A'), CHR(66)65, 'B'
S1 & S2the two strings joined"Ali" & " " & "Raza""Ali Raza"
MID counts from 1, and its third value is a length, not an end position: MID("Lahore", 2, 3) is 3 characters from position 2, "aho" - not positions 2 to 3.
How do you get the last character of any string S? RIGHT(S, 1) or MID(S, LENGTH(S), 1).

The string patterns

Almost every string task is one of these four patterns, or two of them together.

1Visit every character

A FOR loop from 1 to LENGTH(S); inside it, MID(S, i, 1) is the character at position i.

Use it when the question says count the letters …, check every character …, find any …

index12345678
S'A''l''i'' ''R''a''z''a'
When i = 4, MID(S, i, 1) is ' ' (a space).
Template
FOR i ← 1 TO LENGTH(S)   Ch ← MID(S, i, 1)   // do something with ChNEXT i 

Trap Looping FOR i ← 0 TO LENGTH(S) or FOR i ← 1 TO LENGTH(S) + 1 goes outside the string.

2Build a new string

Start with the empty string "" and add (&) the characters you want to keep, one at a time.

Use it when the question says remove …, change every …, reverse …, encrypt …, return the string with …

index1234
Result'A''l''i''R'
Removing the spaces from "Ali R": each kept character is added at the end of Result.
Template
Result ← ""FOR i ← 1 TO LENGTH(S)   Ch ← MID(S, i, 1)   IF Ch <> ' ' THEN      Result ← Result & Ch   ENDIFNEXT i 

Trap Forgetting Result ← "" before the loop. For a reverse, add the new character at the front: Result ← Ch & Result.

3Find a position

Search the string until you find what you want; remember WHERE with a variable, and stop with a flag.

Use it when the question says the first …, where …, everything before / after …

index12345678
Line'X''<''-''5''/''/''g''o'
Looking for "//": compare MID(Line, i, 2) with "//". Found at position 5.
Template
Pos ← 0i ← 1WHILE i <= LENGTH(Line) - 1 AND Pos = 0   IF MID(Line, i, 2) = "//" THEN      Pos ← i   ENDIF   i ← i + 1ENDWHILE// Pos = 0 means "not found" 

Trap When you look at 2 characters at a time, stop at LENGTH - 1, or MID runs past the end.

4Split at a separator

Find the separator (pattern 3), then LEFT gives what comes before it and MID / RIGHT what comes after.

Use it when the question says each line of the file holds a name and a score separated by a comma …

index123456
Data'A''l''i'',''1''7'
"Ali,17": the comma is at position 4. Before it: LEFT(Data, 3). After it: RIGHT(Data, 2).
Template
// after finding the comma at position Pos:Name ← LEFT(Data, Pos - 1)Age  ← STR_TO_NUM(RIGHT(Data, LENGTH(Data) - Pos)) 

Trap Off by one: before the comma is Pos - 1 characters; after it is LENGTH - Pos characters.

Checking what kind of character it is

Character tests (characters compare by their character codes)
IF Ch >= 'A' AND Ch <= 'Z' THEN      // an upper-case letterIF Ch >= 'a' AND Ch <= 'z' THEN      // a lower-case letterIF Ch >= '0' AND Ch <= '9' THEN      // a digit (or: IS_NUM(Ch))IF Ch = ' ' THEN                     // a space

Worked example: initials

Example 1 · Initials (own example) ★★ Medium
Q1Practice5 marks

Input a full name such as "Muhammad ali Khan". Output the initials in capitals: "MAK". Names are separated by single spaces.

1 Read it with me what is actually happening?

An initial is the first letter of each name. The first name starts at position 1; every other name starts just after a space.

  • initialsthe first letter of each word
  • in capitalsTO_UPPER at the end, because the input may be small letters
2 What is it asking for? the target, part by part
  • 1a string of first lettersbuilt up one character at a time (pattern 2)
3 What do we know? everything the question gives us
  • "Muhammad ali Khan"the input
  • ' 'the separator
  • A character is the start of a word when the character before it is a space.
  • Position 1 has no character before it: handle it on its own.
4 Plan the route work backwards from what we want
FindKey ideaAlready have itWork out firstTrap
  • FindInitials
    • Already have itfirst letter = LEFT(FullName, 1)
    • Work out firstevery i where MID(FullName, i - 1, 1) = ' '
      • Key ideapattern 1 + pattern 2
    • Trapstart the loop at 2, so i - 1 is never 0
Why not look for the space and take the character after it?

That works too (take MID(FullName, i + 1, 1) when MID(FullName, i, 1) = ' '): then stop the loop at LENGTH - 1.

When do we make it upper case?

Once at the end: TO_UPPER(Initials). (Or UCASE on each character.)

5 Now solve it have a go on paper first, then open the worked solution
  1. Start Initials with the first character.
  2. Loop i from 2 to LENGTH: if the character at i - 1 is a space, add the character at i.
  3. Output TO_UPPER(Initials).
Model answer
DECLARE FullName, Initials : STRINGDECLARE Ch : CHARDECLARE i : INTEGERINPUT FullNameInitials ← LEFT(FullName, 1)FOR i ← 2 TO LENGTH(FullName)   IF MID(FullName, i - 1, 1) = ' ' THEN      Ch ← MID(FullName, i, 1)      Initials ← Initials & Ch   ENDIFNEXT iOUTPUT TO_UPPER(Initials)
6 Check it does the answer make sense?

Tested: "Muhammad ali Khan" → MAK, and a single name "Sara" → S (the loop adds nothing).

Practice: three levels

L1 Basic

One function or one loop.

L1.1 First, last and length

Input a word. Output its length, its first character and its last character.

Show the model answer
DECLARE Word : STRINGINPUT WordOUTPUT LENGTH(Word)OUTPUT LEFT(Word, 1)OUTPUT RIGHT(Word, 1)

L1.2 One character per line

Input a word and output each of its characters on a separate line.

Show the model answer
DECLARE Word : STRINGDECLARE i : INTEGERINPUT WordFOR i ← 1 TO LENGTH(Word)   OUTPUT MID(Word, i, 1)NEXT i

Pattern 1 on its own.

L1.3 Count the a's

Input a sentence. Output how many times the letter a appears, small or capital.

Hint

How can one comparison catch 'A' and 'a'?

Show the model answer
DECLARE Sentence : STRINGDECLARE Count, i : INTEGERINPUT SentenceCount ← 0FOR i ← 1 TO LENGTH(Sentence)   IF LCASE(MID(Sentence, i, 1)) = 'a' THEN      Count ← Count + 1   ENDIFNEXT iOUTPUT Count

LCASE turns 'A' into 'a', so one test catches both.

L2 Medium

Build a new string or compare positions.

L2.1 Reverse

Input a word and output it backwards ("Lahore" → "erohaL").

Show the model answer
DECLARE Word, Result : STRINGDECLARE i : INTEGERINPUT WordResult ← ""FOR i ← 1 TO LENGTH(Word)   Result ← MID(Word, i, 1) & ResultNEXT iOUTPUT Result

Adding each character at the front reverses the order. (Or loop i from LENGTH down to 1 STEP -1 and add at the end.)

L2.2 No spaces

Input a sentence and output it with every space removed.

Show the model answer
DECLARE S, Result : STRINGDECLARE i : INTEGERINPUT SResult ← ""FOR i ← 1 TO LENGTH(S)   IF MID(S, i, 1) <> ' ' THEN      Result ← Result & MID(S, i, 1)   ENDIFNEXT iOUTPUT Result

Pattern 2 with a test.

L2.3 Is it a palindrome?

Input a word. Output TRUE if it reads the same backwards (ignore capitals: "Level" is a palindrome), otherwise FALSE.

Hint

Which position is the mirror of position 1? Of position 2?

Show the model answer
DECLARE Word : STRINGDECLARE i : INTEGERDECLARE Same : BOOLEANINPUT WordWord ← TO_LOWER(Word)Same ← TRUEFOR i ← 1 TO LENGTH(Word) DIV 2   IF MID(Word, i, 1) <> MID(Word, LENGTH(Word) - i + 1, 1) THEN      Same ← FALSE   ENDIFNEXT iOUTPUT Same

Compare position i with its mirror position LENGTH - i + 1. Only half the word needs checking. (Using L2.1 and comparing the reversed word with the word is fine too.)

L3 Hard

Two or three patterns together.

L3.1 Name and score

A string holds a name and a score separated by a comma, e.g. "Hamza,73". Output Hamza scored 73, and then Pass if the score is 50 or more, otherwise Fail.

Hint

Write "Hamza,73" in boxes numbered 1 to 8. Where is the comma? How many characters come after it?

Show the model answer
DECLARE Data, Name : STRINGDECLARE Pos, i, Score : INTEGERINPUT DataPos ← 0FOR i ← 1 TO LENGTH(Data)   IF MID(Data, i, 1) = ',' THEN      Pos ← i   ENDIFNEXT iName ← LEFT(Data, Pos - 1)Score ← STR_TO_NUM(RIGHT(Data, LENGTH(Data) - Pos))OUTPUT Name, " scored ", ScoreIF Score >= 50 THEN   OUTPUT "Pass"ELSE   OUTPUT "Fail"ENDIF

Pattern 3 finds the comma, pattern 4 splits. STR_TO_NUM is needed before comparing with 50: the string "73" is not a number.

L3.2 Strong password

Input a password. It is Strong if it has at least 8 characters, at least one capital letter and at least one digit. Otherwise output Weak.

Show the model answer
DECLARE Pwd : STRINGDECLARE Ch : CHARDECLARE i : INTEGERDECLARE HasUpper, HasDigit : BOOLEANINPUT PwdHasUpper ← FALSEHasDigit ← FALSEFOR i ← 1 TO LENGTH(Pwd)   Ch ← MID(Pwd, i, 1)   IF Ch >= 'A' AND Ch <= 'Z' THEN      HasUpper ← TRUE   ENDIF   IF Ch >= '0' AND Ch <= '9' THEN      HasDigit ← TRUE   ENDIFNEXT iIF LENGTH(Pwd) >= 8 AND HasUpper = TRUE AND HasDigit = TRUE THEN   OUTPUT "Strong"ELSE   OUTPUT "Weak"ENDIF

One flag per rule, all set FALSE before the loop; the decision comes after the loop, when every character has been seen.

L3.3 Remove a comment

A line of pseudocode may end with a comment that starts with //. Input a line and output it without the comment and without the spaces that were in front of the comment. A line with no comment is output unchanged.

Example: "Total ← 0 // reset" → "Total ← 0"

Show the model answer
DECLARE Line, Result : STRINGDECLARE Pos, i : INTEGERINPUT LinePos ← 0i ← 1WHILE i <= LENGTH(Line) - 1 AND Pos = 0   IF MID(Line, i, 2) = "//" THEN      Pos ← i   ENDIF   i ← i + 1ENDWHILEIF Pos = 0 THEN   Result ← LineELSE   Result ← LEFT(Line, Pos - 1)ENDIFWHILE LENGTH(Result) > 0 AND RIGHT(Result, 1) = ' '   Result ← LEFT(Result, LENGTH(Result) - 1)ENDWHILEOUTPUT Result

Find "//" (pattern 3, stopping at the first one), keep what is before it (pattern 4), then cut spaces off the end one at a time. This is exactly the kind of module the last question of a 2024 paper asked for.

Mistakes that lose marks

MistakeWrite this instead
Treating the third value of MID as an end positionIt is a length: MID(S, 5, 2) = positions 5 and 6
Comparing a number with a string: IF "73" > 50Convert first: STR_TO_NUM(Part) > 50
Joining a number: "Score " & Score"Score " & NUM_TO_STR(Score)
Looking at 2 characters up to LENGTH(S)Stop at LENGTH(S) - 1
Comparing a CHAR with double quotesBoth work in practice, but write single quotes for one character: Ch = 'a'

Can I do this?

Anything unticked: revise that section first. All ticked: take the quiz.

The multiple-choice and guided questions need JavaScript. The concept checks and exam practice below work without it.

Concept checks

Answer each one in your head first, then open it.

1Why does the reverse pattern add the character at the front?Show answer

Each new character comes from further right in the word, so putting it in front builds the word backwards.

2Why must the result string be set to "" before the loop?Show answer

The loop adds to whatever is already there; without a starting value it would be undefined (or left over from before).

3How is a string like a 1D array?Show answer

Both are rows of items with positions starting at 1: MID(S, i, 1) is like A[i]. The same loop visits every item.

Your progress on this note is saved when JavaScript is on.

⬇️ Download this chapter as a PDF: Full notes · Worksheets · Answers