View
213
Download
0
Tags:
Embed Size (px)
Citation preview
Motivation
• One of the most powerful programming tools available
• Help to organize a collection of homogeneous data items (same type and lenght). The individual data items that make up the array are called as Element of the array
• Example: Scores[3] indicated the third exam score
Operation on Arrays
• Loading initial value into the element of array
• Processing the elements of the array
• Searching an array (linear or binary search)
• Writing out the array content to the report
Example 7.1
Find the sum of the elements of an array
• Each elemen 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)
ENDO
Print sum
END
Example 7.2 Find the average of the elements of an array
• 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)
ENDO
Average = sum / number_of_elements
Print average
END
Example 7.3 Find the largest elements of an array
• 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_elementSet largest_element to array(1)DO index = 2 to number_of_elements
IF array(index) > largest_element THENlargest_element = array(index)
ENDIFENDOPrint largest_element
END
Example 7.4 Find the smallest of the elements of an array
• 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 then looks at the other elements of the array to see if a smaller value exists. The smallest value is then printed.
Find_smallest_elementSet smallest_element to array (1)DO index = 2 to number_of_elements
IF array(index) < smallest_element THEN
smallest_element = array(index)ENDIF
ENDOPrint smallest_element
END
Find_range_of_element Set smallest_element to array(1)Set largest_element to array(1)DO index = 2 to number_of_elements
IF array(index) < smallest_element THENsmallest_element = array(index)
ELSEIF array(index) > largest_element THEN
largest_element = array(index)ENDIF
ENDIFENDOPrint the range as smallest_element followed by largest_element
END
Initialising the elements of an array
• Because an array is an iternal data structure, initial values must be placed into the array before any information can be retrieved from it.
• The initial values can be assigned to the element as constant or be read from file.
1. Loading constant values into array (only be used for data which is unlikely to be changed)
Initialise_month_tablemonth_table(1) = `Januari`month_table(2) = `February`
.
.
.month_table(12) = `December`
END
2. Loading initial values into an array from an input file
Read_values_into_arraySet max_num_elements to required valueSet index to zeroRead first input valueDOWHILE (input value exist) AND (index<max_num_elements)
index = index + 1array(index) = input valueRead next input value
ENDDOIF (input value exist) AND index = max_num_elements THEN
Print `Array size is too small`ENDIF
END
Array of variable sizeRead_values_into_variable_array
Set max_num_elements to required valueSet index to zeroRead first input valueDOWHILE (input value NOT = 9999) AND (index<max_num_elements)
index = index + 1array(index) = input valueRead next input value
ENDDOIF index < max_num_elements THEN
index = index + 1array(index) = 9999
ELSEPrint `Array size is too small`
ENDIFEND
Sentinel value indicate the end of input records during initial processing and the last element of the array during further processing
Paired Arrays
• Two array with the same number of elements are paired because they correspond each other.
• Example:– A student number ID array and student name
array
Read_values_into_paired_arraySet max_num_elements to required valueSet index to zeroRead first input valueDOWHILE (NOT EOF input record) AND (index<max_num_elements)
index = index + 1product_codes(index) = input_product_codeselling_prices (index) = input_selling_priceRead next record
ENDDOIF (NOT EOF input record) AND index = max_num_elements THEN
Print `Array size is too small`ENDIF
END
Paired Arrays Example(Algorithm to read a file of product codes and corresponding selling
price and load them into corresponding arrays)
Searching an Array
• The reason: – To edit an input value (ie. Valid element or
not)– To retrieve information from array– To retrieve information from corresponding
element in a paired array.
Linear search array
Linear_search_of_an_arraySet max_num_elements to required valueSet element_found to falseSet index to 1DOWHILE (NOT element_found) AND (index <= max_num_elements)
IF array(index) = input_value THENSet element_found to true
ELSEindex = index + 1
ENDIFENDDOIF element_found THEN
Print array (index)ELSE
Print ´value not found´, input_valueENDIF
END
Binary Search Array(effective method for elements more than 25 and sorted into ascending sequence)
Binary_search_of_an_arraySet element_found to falseSet low_element to 1Set high_element to max_num_elementsDOWHILE (NOT element_found) AND (low_element <= high_elements)
index = (low_element + high_element)/2IF input_value = array(index) THEN
Set element_found to trueELSE IF input_value < array (index) THEN
high_element = index – 1 ELSE
low_element = index + 1 ENDIFENDIF
ENDDOIF element_found THEN
Print array (index)ELSE
Print ´value not found´, input_valueENDIF
END
Writing out the contents of an Array
Write_values_of_array
DO index = 1 to number_of_elements
Print array (index)
ENDDO
END
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.
• Defining diagram
Input Processing Output
18 exam scores Prompt the scoresGet scoresCompute class averageDisplay scoresDisplay class average
18 exam scoresClass_average
Control Structures required
1. An array to store the exam scores – called ´scores´
2. An index to identify each element in the array
3. A DO loop to accept the scores
4. Another DO loop to display the scores to the screen.
Solution AlgorithmProcess_exam_scores
Set total_score to zeroDO index = 1 to 18
Prompt operator for scoreGet scores(index)total_score = total_score + scores(index)
ENDDOCompute average_score = total_score / 18DO index = 1 to 18
Display scores(index)ENDDODisplay 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 average.
• Defining diagram
Input Processing Output
100 integer values Read integer valuesCompute integer valuesCompute integer countDisplay integer averageDisplay integer count
Integer_averageinteger_count
Control Structures required
1. An array of integer values – called ´numbers´
2. A DO loop to calculate the average of the integers
3. Another DO loop to count the number of integers greater than the average.
Solution AlgorithmProcess_integer_array
Set integer_total to zeroSet integer_count to zeroDO index = 1 to 100
integer_total = integer_total + numbers(index)ENDDOinteger_average = integer_total / 100DO index = 1 to 100
IF numbers(index) > integer_average THENadd 1 to integer_count
ENDIFENDDODisplay 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 verifief against an array of 35 sales numbers. Any sales number not found in the array is to be flagged as an error.
• Defining diagram
Input Processing Output
Sales_record• Sales_number
Read sales recordsValidate sales numbersPrint error message
Error_message
Control Structures required
1. A previously initialised array of sales numbers, called ´sales_numbers´
2. A DOWHILE loop to read the sales file
3. A DOWHILE loop to perform linear search
4. A variable element_found to stop the search
Solution AlgorithmValidate_sales_numbers
Set max_num_elements to 35Read sales recordDOWHILE sales_records exist
Set element_found to falseSet index to 1DOWHILE (NOT element_found) AND (index <= max_num_elements)
IF sales_numbers(index) = input sales number THENSet element_found to true
ELSEindex = index + 1
ENDIFENDDOIF NOT element_found THEN
Print `invalid sales numer`, input sales numberENDIFRead sales record
ENDDOEND
Example 7.9 Calculate shipping Charge
• Design an algorithm that will read an input weight for an item to be shipped, search an array of shipping weigths and retrieve a corresponding shipping charge. In this algorithm, two paired arrays, each containing six elements, have been established and initialised. The array, shipping_weights, contains a range of shipping weights in grams, and the array, shipping_charges, contains a corresponding array of shipping charges in dollars, as follows:
Shipping weights (grams)
Shipping 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
• Defining diagram
Input Processing Output
Entry weight Prompt for entry weightGet entry weightSearch shipping weight arrayComputer shipping chargesDisplay shipping charge
Shipping_chargeerror_message
Control Structures required
1. Two arrays, called ´shipping_weigths´ and ´shipping_charges`
2. A DOWHILE loop to search the shipping_weigths array and then retrieve the shipping_charges
3. A variable element_found to stop the search when entry weight is found
Solution AlgorithmCalculate_shipping_charge
Set max_num_elements to 6Read index to 1Set element found to falsePrompt for entry weigthGet entry weightDOWHILE (NOT element_found) AND (index <= max_num_elements)
IF shipping_weights(index) < entry weight THENadd 1 to index
ELSEset element_found to true
ENDIFENDDOIF element_found THEN
shipping_charge = shipping charges(index)Display `shipping charge is`, shipping_charge
ELSEDisplay `invalid shipping weight`, entry weight
ENDIFEND
Two-dimensional Arrays
• Where two subscripts are required to locate an element in an array.
• The number of elements is calculated as the product of the number of rows and the number of columns
• Specified by: array(row_index,column_index)
One dimensional Array
Shipping weights (grams)
1 – 100
101 – 500
501 – 1000
1001 – 3000
3001 – 5000
5001 - 9999
Two dimensional Array
Shipping charges ($) (by shipping zone)
1 2 3 4
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.00 20.00 27.50
32.00 34.00 35.00 38.00
Loading a two-dimensional array(from previous table)
Read_values_into_arraySet max_num_elements to 24Set row_index to zeroRead input fileDOWHILE (input values exist) AND (row_index < 6)
row_index = row_index + 1DO column_index = 1 to 4
shipping_charges(row_index,column_index) = input value
read input fileENDDO
ENDDOIF (input values exist) AND row_index = 6 THEN
Print ´Array size to small`ENDIF
END
Searching Two dimensional Array
Calculate_shipping_ChargesSet row_index to 1Set element_found to falsePrompt for shipping_weight, zoneGet shipping_weight, zoneDOWHILE (NOT element_found) AND (row_index <= 6)
IF shipping_weights(row_index) < input shipping_weight THEN add 1 to row_indexELSE set element_found to trueENDIF
ENDDOIF element_found THEN
IF zone = (1 or 2 or 3 or 4) THEN shipping_charge = shipping_charges(row_index, zone) display ´shipping charge is`, shipping_chargeELSE display `invalid zone`, zoneENDIF
ELSEDisplay `invalid shipping weight`, input shipping_weight
ENDIFEND