0% found this document useful (0 votes)
169 views

07 Array Processing

This document discusses arrays and array processing. It defines arrays as a data structure for organizing homogeneous data under a single name. Elements within an array are accessed using an index or subscript. Common array operations include initializing element values, searching, and writing out contents. The document provides pseudocode examples for initializing arrays from constants or files, and for common tasks like summing, averaging, finding min/max elements. It also discusses two-dimensional and variable-sized arrays.

Uploaded by

RakaBeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
169 views

07 Array Processing

This document discusses arrays and array processing. It defines arrays as a data structure for organizing homogeneous data under a single name. Elements within an array are accessed using an index or subscript. Common array operations include initializing element values, searching, and writing out contents. The document provides pseudocode examples for initializing arrays from constants or files, and for common tasks like summing, averaging, finding min/max elements. It also discusses two-dimensional and variable-sized arrays.

Uploaded by

RakaBeta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

7.

Array processing

Objectives

To introduce arrays and the uses of arrays


To develop pseudocode algorithms for common operations on arrays
To illustrate the manipulation of single- and two-dimensional arrays

Outline

Array processing
Initializing the elements of an array
Searching an array
Writing out the contents of an array
Programming examples using arrays
Two-dimensional arrays
Chapter summary
Programming problems

73

1.

Array processing

Arrays are one of the most powerful programming tools available. They provide the
programmer with a way of organizing a collection of homogeneous data items (that is, items that
have the same type and the same length) into a single data structure. An array, then, is a data
structure that is made up of a number of variables all of which have the same data type for
example, all the exam scores for a class of 30 mathematics students. By using an array, a single
variable name such as scores can be associated with all 30 exam scores.
The individual data items that make up the array are referred to as the elements of the array.
Elements in the array are distinguished from one another by the use of an index or subscript,
enclosed in parentheses, following the array name for example: scores (3).
The subscript indicates the position of an element within the array; so, scores (3) refers to the
third exam score, or the third element of the array scores, and scores (23) refers to the 23rd
exam score.
The subscript or index may be a number or a variable, and may then be used to access any item
within the valid bounds of an array for example:
scores(6), or
element(index)

Arrays are an internal data structure that is, they are required only for the duration of the
program in which they are defined. They are a very convenient mechanism for storing and
manipulating a collection of similar data items in a program, and a programmer should be
familiar with the operations most commonly performed on them. Arrays are sometimes referred
to as tables.

Operations on arrays
Arrays can be used:

to load initial information into an array that is later required for processing
to process the elements of the array
to store the results of processing into the elements of an array, or
to store information, which is then written to a report.

Thus, the most typical operations performed on arrays are:

loading a set of initial values into the elements of an array


processing the elements of an array
searching an array, using a linear or binary search, for a particular element
writing out the contents of an array to a report.

Usually, the elements of an array are processed in sequence, starting with the first element. This
can be accomplished easily in pseudocode with either a DO loop or a DOWHILE loop.

Simple algorithms that manipulate arrays


The following algorithms involve the simple manipulation of arrays. Each algorithm is written
using a DO loop. In each algorithm, the contents of the array and the number of elements have

74

been established and the subscript is named index. The number of elements in the array is
stored in the variable number_of_elements.

EXAMPLE 7.1 Find the sum of the elements of an array


In this example, each element of the array is accumulated into a variable called sum. When all
elements have been added, the variable sum is printed.
Find_sum_of_elements
Set sum to zero
DO index = 1 to number_of_elements
sum = sum + array (index)
ENDDO
Print sum
END

EXAMPLE 7.2 Find the mean (average) of the elements of an array


In this example, each element of the array is accumulated into a variable called sum. When all
elements have been added, the average of the elements is found and printed.
Find_element_average
Set sum to zero
DO index = 1 to number_of_elements
sum = sum + array (index)
ENDDO
average = sum / number_of_elements
Print average
END

EXAMPLE 7.3 Find the largest of the elements of an array


In this example, the elements of an array are searched to determine which element is the largest.
The algorithm starts by putting the first element of the array into the variable largest_element,
and then looks at the other elements of the array to see if a larger value exists. The largest value
is then printed.
Find_largest_element
Set largest_element to array (1)
DO index = 2 to number_of_elements
IF array (index) > largest_element THEN
largest_element = array (index)
ENDIF
ENDDO
Print largest_element
END

EXAMPLE 7.4 Find the smallest of the elements of an array


In this example, the elements of an array are searched to determine the smallest element. The
algorithm starts by putting the first element of the array into the variable smallest_element, and

75

then looks at the other elements of the array to see if a smaller value exists. The smallest value is
then printed.
Find_smallest_element
Set smallest_element to array (1)
DO index = 2 to number_of_elements
IF array (index) < smallest_element THEN
smallest_element = array (index)
ENDIF
ENDDO
Print smallest_element
END

EXAMPLE 7.5 Find the range of the elements of an array


In this example, the elements of an array are searched to determine the smallest and the largest
elements. The algorithm starts by putting the first element of the array into the variables
smallest_element and largest_element, and then looks at the other elements to see if a smaller or
larger value exists. The two values are then printed.
Find_range_of_elements
Set smallest_element to array (1)
Set largest_element to array (1)
DO index = 2 to number_of_elements
IF array (index) < smallest_element THEN
smallest_element = array (index)
ELSE
IF array (index) > largest_element THEN
largest_element = array (index)
ENDIF
ENDIF
ENDDO
Print the range as smallest_element followed by largest_element
END

2.

Initializing the elements of an array

Because an array is an internal data structure, initial values must be placed into the array before
any information can be retrieved from it. These initial values can be assigned to the elements of
the array as constants, or they can be read into the array from a file.

Loading constant values into an array


This method should only be used when the data in the array is unlikely to be changed for
example, the names of the 12 months of the year. To initialize such an array, establish an array
called month_table, which contains 12 elements all of the same size. Then assign the elements of
the array with the names of the months, one by one, as follows:
Initialize_month_table
month_table(1) = January
month_table(2) = February
:
:
month_table(12) = December

76

END

Note that each element of the array must be the size of the largest month that is, September
so, the shorter month names must be padded with blanks.

Loading initial values into an array from an input file


Defining array elements as constants in a program is not recommended if the values change
frequently, as the program will need to be changed every time an array element changes. A
common procedure is to read the input values into the elements of an array from an input file.
The reading of a series of values from a file into an array can be represented by a simple
DOWHILE loop. The loop should terminate when either the array is full or the input file has
reached end of file. Both of these conditions can be catered for in the condition clause of the
DOWHILE loop.
In the following pseudocode algorithm, values are read from an input file and assigned to the
elements of an array, starting with the first element. until there are no more input values or the
array is full. The array name is array, the subscript is index, and the maximum number of
elements that the array can hold is max_num_elements.
Read_values_into_array
Set max_num_elements to required value
Set index to zero
Read first input value
DOWHILE (input values exist) AND (index < max_num_elements)
index = index + 1
array (index) = input value
Read next input value
ENDDO
IF (input values exist) AND index = max_num_elements THEN
Print Array size too small
ENDIF
END

Note that the processing will terminate when either the input file has reached EOF or the array
is full. An error message will be printed if there are more input data items than there are
elements in the array.

Arrays of variable size


In some programs, the number of entries in an array can vary. In this case, a sentinel value (for
example, 9999) is used to mark the last element of the array, both in the initializing file of data
items and in the array itself. The sentinel record will indicate the end of input records during
initial processing and the last element of the array during further processing: The algorithm for
loading values into an array of variable size must include a check to ensure that no attempt is
made to load more entries into the array than there are elements, as in the following example:
Read_values_into_variable_array
Set max_num_elements to required value
Set index to zero
Read first input value
DOWHILE (input value NOT = 9999) AND (index < max_num_elements)
index = index + 1
array (index) = input value

77

Read next input value


ENDDO
IF index < max_num_elements THEN
index = index + 1
array (index) = 9999
ELSE
Print Array size too small
ENDIF
END

Note that the processing will terminate when either the sentinel record has been read or the
array is full. An error message will be printed if there are more input data items than there are
elements in the array.

Paired arrays
Many arrays in business applications are paired that is, there are two arrays that have the
same number of elements. The arrays are paired because the elements in the first array
correspond to the elements in the same position in the second array. For example, a sales
number array can be paired with a sales name array. Both arrays would have the same number
of elements, with corresponding sales numbers and sales names. When you have determined
where in the sales number array a particular salespersons number appears, retrieve the
salespersons name from the corresponding position in the sales name array. In this way, the
salespersons number and name can appear on the same report, without any extra keying.
In the following example, an algorithm has been designed to read a file of product codes and
corresponding selling prices for a particular company and to load them into two corresponding
arrays, named product_codes and selling_prices. In the algorithm, the subscript is index, and
the field max_num_elements contains the total number of elements in each array.
Read_values_into_paired_arrays
Set max_num_elements to required value
Set index to zero
Read first input record
DOWHILE (NOT EOF input record) AND (index < max_num_elements)
index = index + 1
product_codes (index) = input product_code
selling_prices (index) = input selling_price
Read next record
ENDDO
IF (NOT EOF input record) AND index = max_num_elements THEN
Print Array size too small
ENDIF
END

3.

Searching an array

A common operation on arrays is to search the elements of an array for a particular data item.
The reasons for searching an array may be:

78

to edit an input value that is, to check that it is a valid element of an array
to retrieve information from an array
to retrieve information from a corresponding element in a paired array.

When searching an array, it is an advantage to have the array sorted into ascending sequence,
so that, when a match is found, the rest of the array does not have to be searched. If you find an
array element that is equal to an in put entry, a match has been found and the search can be
stopped. Also, if you find an array element that is greater than an input entry, no match has
been found and the search can be stopped. Note that if the larger entries of an array are
searched more often than the smaller entries, it may be an advantage to sort the array into
descending sequence.
An array can be searched using either a linear search or a binary search.

A linear search of an array


A linear search involves looking at each of the elements of the array, one by one, starting with
the first element. Continue the search until either you find the element being looked for or you
reach the end of the array. A linear search is often used to validate data items.
The pseudocode algorithm for a linear search of an array will require a program flag named
element_found. This flag, initially set to false, will be set to true once the value being looked for
is found that is, when the current element of the array is equal to the data item being looked
for. In the following algorithm, the data item being searched for is stored in the variable
input_value, and max_num_elements contains the total number of elements in the array.
Linear_search_of_an_array
Set max_num_elements to required value
Set element_found to false
Set index to 1
DOWHILE (NOT element_found) AND (index < = max_num_elements)
IF array (index) = input_value THEN
Set element_found to true
ELSE
index = index + 1
ENDIF
ENDOO
IF element_found THEN
Print array (index)
ELSE
Print value not found, input_value
ENDIF
END

A binary search of an array


When the number of elements in an array exceeds 25. and the elements are sorted into
ascending sequence, a more efficient method of searching the array is a binary search.
A binary search locates the middle element of the array first, and determines if the element
being searched for is in the first or second half of the table. The search then points to the middle
element of the relevant half table, and the comparison is repeated. This technique of continually
halving the area under consideration is continueduntil the data item being searched for is
found, or its absence is detected.
In the following algorithm, a program flag named element_found is used to indicate whether the
data item being looked for has been found. The variable low_element indicates the bottom

79

position of the section of the table being searched, and high_element indicates the top position.
The maximum number of elements that the array can hold is placed in the variable
max_num_elements.
The binary search will continue until the data item has been found, or there can be no more
halving operations (that is, low_element is not less than high_element).
Binary_search_ of_an_array
Set element_found to false
Set low_element to 1
Set high_element to max_num_elements
DOWHILE (NOT element_found) AND (low_element < = high_element)
index = (low_element + high_element) / 2
IF input_value = array (index) THEN
Set element_found to true
ELSE
IF input_value < array (index) THEN
high_element = index - 1
ELSE
low_element = index + 1
ENDIF
ENDIF
ENDDO
IF element_found THEN
Print array (index)
ELSE
Print value not found, input_value
ENDIF
END

4.

Writing out the contents of an array

The elements of an array can be used as accumulators of data, to be written to a report. Writing
out the contents of an array involves starting with the first element of the array and continuing
until all elements have been written. This can be represented by a simple DO loop.
In the following pseudocode algorithm, the name of the array is array and the subscript is
index. The number of elements in the array is represented by number_of_elements.
Write_values_of_array
DO index = 1 to number_of_elements
Print array (index)
ENDDO
END

5.

Programming examples using arrays

EXAMPLE 7.6 Process exam scores


Design a program that will prompt for and receive 18 examination scores from a mathematics
test, compute the class average, and display all the scores and the class average to the
screen.

80

A Defining diagram
Input

Processing

Output

18 exam scores

Prompt for scores


Get scores
Compute class average
Display scores
Display class average

18 exam scores
class_average

B Control structures required


1.
2.
3.
4.

An array to store the exam scores that is, scores.


An index to identify each element in the array.
A DO loop to accept the scores.
Another DO loop to display the scores to the screen.

C Solution algorithm
Process_exam_scores
Set total_score to zero
DO index = 1 to 18
Prompt operator for score
Get scores (index)
total_score = total_score + scores (index)
ENDDO
Compute average_score = total_score / 18
DO index = 1 to 18
Display scores (index)
ENDDO
Display average_score
END

EXAMPLE 7.7 Process integer array


Design an algorithm that will read an array of 100 integer values, calculate the average integer
value, and count the number of integers in the array that are greater than the average integer
value. The algorithm is to display the average integer value and the count of integers greater
than the average.

A Defining diagram
Input

Processing

Output

100 integer values

Read integer values


Compute integer average
Compute integer count
Display integer average
Display integer count

integer_average
integer_count

B Control structures required


1. An array of integer values that is, numbers.

81

2. A DO loop to calculate the average of the integers.


3. A DO loop to count the number of integers greater than the average.
C Solution algorithm
Process_integer_array
Set integer_total to zero
Set integer_count to zero
DO index = 1 to 100
integer_total = integer_total + numbers (index)
ENDDO
integer_average = integer_total / 100
DO index = 1 to 100
IF numbers (index) > integer_average THEN
add 1 to integer_count
ENDIF
ENDDO
Display integer_average, integer_count
END

EXAMPLE 7.8 Validate sales number


Design an algorithm that will read a file of sales transactions and validate the sales numbers on
each record. As each sales record is read, the sales number on the record is to be verified
against an array of 35 sales numbers. Any sales number not found in the array is to be flagged
as an error.

A Defining diagram
Input

Processing

Output

sales records
sales_number

Read sales records


Validate sales numbers
Print error message

error_message

B Control structures required


1. A previously initialized array of sales numbers that is, sales_numbers.
2. A DOWHILE loop to read the sales file.
3. A DOWHILE loop to perform a linear search of the array for the sales number. 4 A
variable element_found that will stop the search when the sales number is found.
C Solution algorithm
Validate_sales_numbers
Set max_num_elements to 35
Read sales record
DOWHILE sales records exist
Set element_found to false
Set index to 1
DOWHILE (NOT element_found) AND (index <= max_num_elements)
IF sales_numbers (index) = input sales number THEN
Set element_found to true
ELSE

82

index = index + 1
ENDIF
ENDDO
IF NOT element_found THEN
Print invalid sales number, input sales number
ENDIF
Read sales record
ENDDO
END

EXAMPLE 7.9 Calculate freight charge


Design an algorithm that will read an input weight for an item to be shipped, search an array of
shipping weights and retrieve a corresponding freight charge. In this algorithm, two paired
arrays, each containing six elements, have been established and initialized. The array,
shipping_weights, contains a range of shipping weights in grams, and the array,
freight_charges, contains a corresponding array of freight charges in dollars, as follows.
Shipping weights (grams)

Freight charges

1-100

3.00

101-500

5.00

501-1000

7.50

1001-3000

12.00

3001-5000

16.00

5001-9999

35.00

A Defining diagram
Input

Processing

Output

entry weight

Prompt for entry weight


Get entry weight
Search shipping weights array
Compute freight charges
Display freight charge

freight_charge
error_message

B Control structures required


1. Two arrays, shipping_weights and freight_charges, already initialized.
2. A DOWHILE loop to search the shipping_weights array and hence retrieve the freight
charge.
3. A variable element_found that will stop the search when the entry weight is found.
C Solution algorithm
Calculate_freight_charge
Set max_num_elements to 6
Set index to 1
Set element_found to false
Prompt for entry weight
Get entry weight
DOWHILE (NOT element_found) AND (index <= max_num_elements)
IF shipping_weights (index) < entry weight THEN

83

add 1 to index
ELSE
Set element_found to true
ENDIF
ENDDO
IF element_found THEN
freight_charge = freight_charges (index)
Display Freight charge is, freight_charge
ELSE
Display invalid shipping weight, entry weight
ENDIF
END

6.

Two-dimensional arrays

So far, all algorithms in this chapter have manipulated one-dimensional arrays that is, only
one subscript is needed to locate an element in an array. In some business applications, there is
a need for multidimensional arrays, where two or more subscripts are required to locate an
element in an array. The following freight charges array is an example of a two-dimensional
array, and is an extension of Example 7.9 above. It is a two-dimensional array because the
calculation of the freight charges to ship an article depends on two values: the shipping weight of
the article, and the geographical area or zone to which it is to be shipped, namely zones 1, 2, 3
or 4.
The range of shipping weights, in grams, is provided in the same one-dimensional array as in
Example 7.9, as follows.
Shipping weights
(grams)
1-100
101-500
501-1000
1001-3000
3001-5000
5001-9999
Freight charges ($) (by shipping zone)
1

2.50

3.50

4.00

5.00

3.50

4.00

5.00

6.50

4.50

6.50

7.50

10.00

10.00

11.00

12.00

13.50

13.50

16.10

20.00

27.50

32.00

34.00

35.00

38.00

In the freight charges array, anyone of four freight charges may apply to a particular shipping
weight, depending on the zone to which the shipment is to be delivered. Thus, the array is set

84

out as having rows and columns, where the six rows represent the six shipping weight ranges,
and the four columns represent the four geographical zones.
The number of elements in a two-dimensional array is calculated as the product of the number
of rows and the number of columns. in this case, 6 x 4 = 24.
An element of a two-dimensional array is specified using the name of the array, followed by two
subscripts, enclosed in parentheses, separated by a comma. The row subscript is specified first,
followed by the column subscript. Thus, an element of the above freight charges array would be
specified as freight_charges (row_index, column_index). So, freight_charges (5, 3) refers to the
freight charge listed in the array where the fifth row and the third column intersect that is, a
charge of $20.00.

Loading a two-dimensional array


A two-dimensional array is loaded in columns within row order that is. all the columns for row
one are loaded before moving to row two and loading the columns for that row, and so on.
In the following pseudocode algorithm, values are read from an input file of freight charges and
assigned to a two-dimensional freight_charges array. The array has six rows, representing the
six shipping weight ranges, and four columns, representing the four geographical shipping
zones, as in the above example.
The reading of a series of values from a file into a two-dimensional array can be represented by
a DO loop within a DOWHILE loop.
Read_ values_into_array
Set max_num_elements to 24
Set row_index to zero
Read input file
DOWHILE (input values exist) AND (row_index < 6)
row_index = row_index + 1
DO column_index = 1 to 4
freight_charges (row_index, column_index) = input value
Read input file
ENDDO
ENDDO
IF (input values exist) AND row_index = 6 THEN
Print Array size too small
ENDIF
END

Searching a two-dimensional array


Search method 1
In the following pseudocode algorithm, the freight charges for an article are to be calculated by
searching a previously initialized two-dimensional array. The input values for the algorithm are
the shipping weight of the article, and the geographical zone to which it is to be shipped.

85

First, the one-dimensional shipping_weights array is searched for the correct weight category
(row_index) and then the two-dimensional freight_charges array is looked up using that weight
category (row_index) and geographical zone (column_index) .
Calculate_Freight_Charges
Set row index to 1
Set element_found to false
Prompt for shipping_weight, zone
Get shipping_weight, zone
DOWHILE (NOT element_found) AND (row_index <= 6)
IF shipping_weights (row_index) < input shipping_weight THEN
add 1 to row_index
ELSE
Set element_found to true
ENDIF
ENDDO
IF element_found THEN
IF zone = (1 or 2 or 3 or 4) THEN
freight_charge = freight_charge (row_index, zone)
Display Freight charge is, freight_charge
ELSE
Display invalid zone, zone
ENDIF
ELSE
Display invalid shipping weight, input shipping_weight
ENDIF
END

Search method 2
In the following algorithm, an input employee number is validated against a two-dimensional
array of employee numbers, which has 10 rows and five columns. The array is searched
sequentially, by columns within rows, using two DOWHILE loops until a match is found. If no
match is found, an error message is printed.
Search_employee_numbers
Set row_index to 1
Set employee_found to false
Read input employee_number
DOWHILE (NOT employee_found) AND (row_index <=10)
Set column_index to 1
DOWHILE (NOT employee_found) AND (column_index <= 5)
IF employee_numbers (row_index, column_index) = input
employee_number THEN
Set employee_found to true
ENDIF
column_index = column_index + 1
ENDDO
row_index = row_index + 1
ENDDO
IF NOT employee_found THEN
Print invalid employee number, input employee_number
ENDIF
END

86

Writing out the contents of a two-dimensional array


To write out the contents of a two-dimensional array, write out the elements in the columns
within a row, before moving on to the next row. This is represented in pseudocode by DO loop
within another DO loop.
In the following pseudocode algorithm, the elements of a two-dimensional array are printed to a
report, by column within row, using two subscripts.
Write_ values_of_array
Set number_of_rows to required value
Set number_of_columns to required value
DO row_index = 1 to number_of_rows
DO column_index = 1 to number_of_columns
Print array (row_index, column_index)
ENDDO
ENDDO
END

Chapter summary
This chapter defined an array as a data structure made up of a number of variables or data
items that all have the same data type and are accessed by the same name. The individual
elements that make up the array are accessed by the use of an index or subscript beside the
name of the array for example, scores (3).
Algorithms were developed for the most common operations on arrays, namely:

loading a set of initial values into the elements of an array


processing the elements of an array
searching an array, using a linear or binary search, for a particular element
writing out the contents of an array to a report

Programming examples using both one and two-dimension arrays were developed.

87

You might also like