Question 1 Report
A program needs to extract and process numeric data from formatted strings.
(a) Write pseudocode for a function ExtractNumber that takes a string like "Price: 45" and returns the numeric value (45 as an integer). The function should find the first digit and extract all consecutive digits from that point. [4]
(b) State the return value for each input. [2]
| Input | Return value |
|---|---|
| "Score: 95 points" | |
| "Room 204" |
(c) Explain the difference between the string "123" and the integer 123. [2]
(a) The ExtractNumber function scans through a string character by character, collecting consecutive digit characters once the first digit is found, then converting the collected digits to an integer.
FUNCTION ExtractNumber(Text : STRING) RETURNS INTEGER
DECLARE NumStr : STRING
DECLARE i : INTEGER
DECLARE Ch : CHAR
DECLARE InNumber : BOOLEAN
NumStr ← ""
InNumber ← FALSE
FOR i ← 1 TO LENGTH(Text)
Ch ← Text[i]
IF Ch >= '0' AND Ch <= '9' THEN
NumStr ← NumStr & Ch
InNumber ← TRUE
ELSE
IF InNumber = TRUE THEN
RETURN INT(STR_TO_NUM(NumStr))
ENDIF
ENDIF
NEXT i
IF NumStr <> "" THEN
RETURN INT(STR_TO_NUM(NumStr))
ENDIF
RETURN 0
ENDFUNCTIONKey logic: the function skips all non-digit characters until the first digit is found. [1] Once digits begin, it collects them into NumStr. [1] When a non-digit is encountered after digits have started, the collected string is converted to a number and returned. [1] If the number is at the end of the string, the post-loop check handles it. [1]
(b)
| Input | Return value |
|---|---|
| "Score: 95 points" | 95 |
| "Room 204" | 204 |
For "Score: 95 points": the function skips non-digits, then finds '9','5', then encounters ' ', so it returns 95. [1]
For "Room 204": the function skips non-digits, then finds '2','0','4'. The post-loop check returns 204. [1]
(c) The string "123" is a sequence of three characters ('1', '2', '3') stored as text data. It cannot be used directly in arithmetic operations. [1] The integer 123 is a single numeric value stored in binary format that can be used directly in calculations such as addition and multiplication. To perform arithmetic on the string, it must first be converted using a function like STR_TO_NUM. [1]
Everything you need to excel in your exams