Question 1 Report
Study the following pseudocode that finds how many unique (distinct) values are in an array.
DECLARE Data : ARRAY[1:8] OF INTEGER
Data contains: [4, 7, 2, 7, 4, 9, 2, 4]
DECLARE UniqueCount : INTEGER
DECLARE IsUnique : BOOLEAN
UniqueCount <- 0
FOR I <- 1 TO 8
IsUnique <- TRUE
FOR J <- 1 TO I - 1
IF Data[J] = Data[I]
THEN
IsUnique <- FALSE
ENDIF
NEXT J
IF IsUnique = TRUE
THEN
UniqueCount <- UniqueCount + 1
OUTPUT Data[I]
ENDIF
NEXT I
OUTPUT "Total unique values: ", UniqueCount
(a) State the output of this program. [3]
(b) Explain the purpose of the inner loop FOR J <- 1 TO I - 1. [2]
(a) Output of the unique-value-finding program with Data = [4, 7, 2, 7, 4, 9, 2, 4]: [3]
4
7
2
9
Total unique values: 4[1] for the correct unique values (4, 7, 2, 9), [1] for correct order (first occurrence of each), [1] for the total count of 4.
Walkthrough: I=1: inner loop J runs 1 to 0 (does not execute), IsUnique stays TRUE, output 4. I=2: J checks Data[1]=4, no match with 7, IsUnique stays TRUE, output 7. I=3: J checks Data[1]=4 and Data[2]=7, no match with 2, output 2. I=4: J checks 4, 7, 2 against 7: Data[2]=7 matches Data[4]=7, IsUnique becomes FALSE, skip. I=5: Data[1]=4 matches Data[5]=4, FALSE, skip. I=6: no match found for 9, output 9. I=7: Data[3]=2 matches Data[7]=2, skip. I=8: Data[1]=4 matches Data[8]=4, skip.
(b) Purpose of the inner loop FOR J <- 1 TO I - 1: [2]
The inner loop checks all elements that appear before the current element (at positions 1 through I-1) to determine whether the current value has already been seen. [1] If any earlier element matches the current value, IsUnique is set to FALSE, indicating this is a duplicate that should not be counted or output again. By only looking backward (not forward), the algorithm ensures that only the first occurrence of each value is counted as unique. [1]
Everything you need to excel in your exams