arrays

storing a set of related data items

Arrays are great for storing a set of related data items.

We can declare one-dimensional arrays:

DECLARE ages : ARRAY[lb : ub] OF INTEGER

where lb is the lowerbound index (often 1 in pseudocode) and ub is the upperbound index

We can assign data to an array.

ages ← [16,15,18,15,19,12,15,17,12,19]

Now we can process the array. If we are going to process the whole array, use a count-controlled loop:

DECLARE teenageCount : INTEGER

teenageCount ← 0

FOR i ← 1 to 10

IF ages[i] >= 13 AND ages[i]<=19

teenageCount ← teenageCOunt + 1

END IF

END FOR

OUTPUT "Teenage count is ", teenageCount

2-dimensional arrays

2-dimensional arrays also organise a set of related data items, but in a structure that looks like a table or spreadsheet.

We can declare two-dimensional arrays:

DECLARE names : ARRAY[rlb : rub, clb:cub] OF STRING

where:

  • rlb is the lowerbound of the row numbers
  • rub is the upperbound of the row numbers
  • clb is the lowerbound of the column numbers
  • cub is the upperbound of the column numbers

We can process a 2D array. If we are going to process the whole array, use a nested count-controlled loop:

DECLARE jackCount : INTEGER

jackCount ← 0

FOR i ← rlb to rub

FOR j ← clb to cub

IF names[i][j] = "jack" OR names[i][j] = "Jack" THEN

jackCount ← jackCount + 1

END IF

END FOR

END FOR

OUTPUT "There are ", jackCount, "Jacks in the array!"

Take a moment to study this code. Can you find the nested for loop?

Take some blank paper. Could you rewrite this algirithm without looking?

Sample Exam Style Question

A 2-dimensional array, colorGrid, stores primary colours, red blue and green.

A sample array of STRINGS might look like this:

 

Task 1

Write pseudocode to determine which has the highest number of occurences in the grid: red, green or blue.

Task 2

Write pseudocode to solve this problem.

If the first item in the row is red and the last item in a row is red, then the middle item in a row will become red.

Every grid always has 4 rows and5 columns, but there could be any number of rows.

Remember to declare the array as you get started.


Study Strategy

Look at the example pseudocode.

Can you think of a similar situation?

Perhaps there is a 2-D array of cities and you want to count how many cities have more than 5 characters in their names.

Could you create your own scenario and write an algorithm to solve a problem you created?


Tags

stay calm think try sleep dream fresh strong spirit