UNIHIVE

Study Hub UNIPORT CSC 288

CSC 288 · Structured Programming

Arrays and string processing

One- and two-dimensional arrays, searching and simple sorting, and handling text with strings.

Our notes

1 min read

Arrays

type ScoreList = array[1..100] of integer;
var scores: ScoreList;
A fixed number of elements of one type, reached by an index. Two dimensions: array[1..5, 1..4] of real for a 5 by 4 table.

Worked example: average and above-average count

for i := 1 to n do total := total + scores[i];
avg := total / n;
count := 0;
for i := 1 to n do
  if scores[i] > avg then count := count + 1;
For scores 45, 70, 62, 38, 85: total 300, average 60.0, three scores (70, 62, 85) are above it.

Linear and binary search

  • Linear search: check each element in turn: up to n comparisons.
  • Binary search (sorted array): compare with the middle, keep the half that can hold the key: at most about log₂ n comparisons.

lo := 1; hi := n; found := false;
while (lo <= hi) and not found do
begin
  mid := (lo + hi) div 2;
  if a[mid] = key then found := true
  else if a[mid] < key then lo := mid + 1
  else hi := mid - 1
end;

A simple sort: selection sort

for i := 1 to n - 1 do
begin
  m := i;
  for j := i + 1 to n do
    if a[j] < a[m] then m := j;
  Swap(a[i], a[m])
end;
It makes about n²/2 comparisons: fine for small arrays (better sorts come with recursion).

Strings

In Turbo and Free Pascal, string holds text; s[1] is the first character and length(s) the length.
Useful routines: copy(s, start, count), pos(sub, s), concat or +, delete, insert, upcase(ch), val and str (convert between text and numbers).

Worked example: counting vowels

count := 0;
for i := 1 to length(s) do
  if upcase(s[i]) in ['A', 'E', 'I', 'O', 'U'] then
    count := count + 1;
For s = 'Port Harcourt' the count is 4 (o, a, o, u).
The set test in [...] is a neat Pascal feature.

Worked example: initials

For the name 'Chinedu Amaka Okafor', take the first letter and every letter after a space: CAO.

Exams usually ask

  • Write programs that process arrays (sum, average, maximum, search).
  • Trace binary search or selection sort.
  • Use string functions to manipulate text.

Common mistake

Going outside the array bounds (a[0] or a[n + 1]). Turn on range checking ({$R+}) while testing so the program stops with a clear error instead of corrupting memory.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

No reading links here yet

Our team adds free books, videos and practice for each topic, and opens every link before it goes up.

All CSC 288 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.