Question 1 Report
A program converts names between different formats.
Format 1: "Smith, John" (surname first, comma separated)
Format 2: "John Smith" (first name first, space separated)
(a) Write pseudocode for a function ToFormat2 that converts from Format 1 to Format 2. [4]
(b) State the output of ToFormat2("Brown, Alice"). [1]
(c) Write pseudocode for a function ToFormat1 that converts from Format 2 to Format 1. [3]
(a) The function finds the comma position, then uses SUBSTRING to extract the surname (before the comma) and first name (after the comma and space): [4]
FUNCTION ToFormat2(Name : STRING) RETURNS STRING
DECLARE CommaPos : INTEGER
DECLARE Surname : STRING
DECLARE FirstName : STRING
DECLARE i : INTEGER
CommaPos ← 0
FOR i ← 1 TO LENGTH(Name)
IF Name[i] = ',' THEN
CommaPos ← i
ENDIF
NEXT i
Surname ← SUBSTRING(Name, 1, CommaPos - 1)
FirstName ← SUBSTRING(Name, CommaPos + 2, LENGTH(Name) - CommaPos - 1)
RETURN FirstName & " " & Surname
ENDFUNCTIONThe key detail is CommaPos + 2: the first name starts two characters after the comma because Format 1 has a comma followed by a space. [1 mark for finding comma position, 1 mark for extracting surname, 1 mark for extracting first name (skipping comma and space), 1 mark for returning concatenated result]
(b) ToFormat2("Brown, Alice") returns "Alice Brown". The comma is at position 5, so Surname = "Brown" (positions 1-5) and FirstName = "Alice" (positions 8-12). [1]
(c) The reverse conversion finds the space and swaps the order, inserting ", " between surname and first name: [3]
FUNCTION ToFormat1(Name : STRING) RETURNS STRING
DECLARE SpacePos : INTEGER
DECLARE FirstName : STRING
DECLARE Surname : STRING
DECLARE i : INTEGER
SpacePos ← 0
FOR i ← 1 TO LENGTH(Name)
IF Name[i] = ' ' THEN
SpacePos ← i
ENDIF
NEXT i
FirstName ← SUBSTRING(Name, 1, SpacePos - 1)
Surname ← SUBSTRING(Name, SpacePos + 1, LENGTH(Name) - SpacePos)
RETURN Surname & ", " & FirstName
ENDFUNCTION[1 mark for finding space, 1 mark for extracting parts, 1 mark for correct format with comma]
Everything you need to excel in your exams