Combine arrays, strings and searches
Store only what the problem needs
Use a 1-D array for one list. Use a 2-D array for a fixed grid of related values. An index identifies a position; the value stored there may be completely different.
Worked example: first longest word
Known words are red, blue and gold. Keep an index of the best word so the name and its length stay connected. Compare with > because an equal length must keep the first word.
DECLARE Words : ARRAY[1:3] OF STRING
DECLARE I, Best : INTEGER
Words[1] ← "red"
Words[2] ← "blue"
Words[3] ← "gold"
Best ← 1
FOR I ← 1 TO 3
IF LENGTH(Words[I]) > LENGTH(Words[Best]) THEN
Best ← I
ENDIF
NEXT I
OUTPUT Words[Best]
Transfer the pattern
Choose whether your answer needs a count, a value or an index. Test one item, no match and repeated equal matches. Explain why starting a greatest-value search at zero fails for all-negative data. Then solve the questions with new inputs.
Read N (1 to 5), then N non-empty names into Names. Count names beginning with uppercase A.
Click Run to see the output here.
Read N (1 to 5), then N non-empty words into an array. Output the longest word; on a tie output the first.
Click Run to see the output here.
Array [4, 9, 4, 2] is searched left to right for 4. Found starts at 0 and is updated only while still 0. Give Found after each of the four comparisons.
Explain your choice of data structure and loop. Identify one boundary case and predict its result. For a subroutine, explain what is returned or changed in the caller.
Saved for this sitting on this browser. Review this yourself or with your teacher; these explanations are not automatically marked.
Review your explanation against these criteria
- My types and data structure match the data and the question.
- I justified the loop and checked its first and last iterations.
- Initial values and rejected operations preserve the intended state.
- My test includes input, purpose and expected result.
- I distinguished returning a value from printing and changing caller state.