Transcript

ARRAYS

1. Basic Ideas2. The Array Type3. Processing Arrays4. Parallel Arrays5. Two-dimensional

Array6. Arrays as

Parameters

1. Basic Idea

using 5 variables to store 5 integers12 16 32 18 27 A B C D E

using an array to store five integers 12 16 32 18 27A[1] A[2] A[3] A[4] A[5]

‘A sub 1’ ‘A sub 2’

1

5

2

3

4

Block A

A B C D E

2. The Array Type

An array– is a structured data type in which a collection

of data items of the same type is stored– entire collection can be referred by using a

single variable name An element

– is the individual item of an array– each can store a value of the declared type– identified by an index or a subscript

2.1. Declaring an array an array type can be defined by the user 2 types - index type (any ordinal type)

– base type (any data type)

arrayarray [index type] [index type] ofof base type base typee.g. Name : array [1..40] of string;

Score : array [1..40] of integer;

Grade: array [1..12] of char;

Xcoordinate : array [-5..5] of real;

– from index type, we know the beginning & ending values the size of the array

2.2. Accessing array elements array name [index]array name [index] e.g. Num: array [1..5] of integer;

e.g. Num [1] := 15;Num [4] := Num[2] + Num [3];

readln (Num[1], Num[2], Num[3]);

writeln (Num[2], Num[3], Num[4]);

if Num[2] > Num[3]

then writeln (Num[2], ‘ is larger ’ );

12345

Num

The array Num

Num [2]

Num [5]

2.3. The type definition section used to - rename predefined types or

- define new data types

e.g. const MaxSize = 40; type NameType = string; ScoreType = integer;

NamArray = array [1..MaxSize] of NameType; ScoreArray = array[1..MaxSize] of ScoreType;

var Name : NameArray; Score : ScoreArray;

is equivalent to

var Name : array[1..40] of string; Score : array[1..40] of integer

2.3. [cont’d]

ExampleWrite a program to read a list of 10 test scores, calculate the average score and print the scores that are above the average

program ProcessMarks;

const NoOf Scores = 10;

varScore1, Score2, Score3, Score4, Score5,

Score6, Score7, Score8, Score9, Score10 : integer;

Average : real;

begin

{ Read the scores}

readln (Score1);

readln (Score2);

readln (Score3);

readln (Score4);

readln (Score5);

readln (Score6);

readln (Score7);

readln (Score8);

readln (Score9);

readln (Score10);

( Calculate the average}

Average := (Score1 + Score2 + Score3 + Score4 + Score5 + Score6 + Score7+ Score8 + Score9 + Score10) ‘ NoOfScores;

{print the scores above average}

if Score1 > Average

then writeln(Score1);

if Score2 > Average

then writeln(Score2);

.

.

if Score10 > Average

then writeln(Score10)

end.

First, a program using separate variables for the test scores.

By using array, the program becomes much simpler and easier to read:

Program ProcessMarks;

{Array version}

const NoOfScores = 10;

type ScoreArray = array[1..NoOfScores] of integer;

var Score : ScoreArray;

Average : real;

i, Total : integer;

begin

{Read the scores}

for i := 1 to NoOfScores do

Readln(Score[ i ]);

Total := 0;

{Calculate the average}

for i := 1 to NoOfScores do

Total := Total + Score[ i ];

Average := Total / NoOfScores;

{Print out scores above average}

for i := 1 to NoOf Scores do

if Score[ i ] > Average

then writeln (Score[ i ])

end.

3. Processing arrays

3.1 Loops for input and output3.2 Loops for assignment3.3 Summing an array3.4 Finding the largest or smallest

value of an array3.5 Searching an array for a target

value3.6 Copying an array

3.1. Loops for input and output input

e.g. for i := 1 to NoOf Scores doreadln(Score[i]);

outpute.g. for i := 1 to NoOfScores do

writeln(Score[i]);

readln(Score);

writeln(Score);

3.2. Loops for assignment to initialize the array Count to zero:

for i := 1 to 10 do

Count[ i ] := 0;

to design a card game, we need to initialize each element of the array CardNo to the value of its own index:for i := 1 to 52 do

Count[ i ] := i ;

3.3. Summing an array

by adding the values of the elements, one at a time, to an accumulator:Total := 0;

for i := 1 to 5 do

Total := Total + Score[ i ];

3.4. Finding the largest & smallest value of an array algorithm:

1. Largest First element2. for each array element do

2.1 if the Current element > Largest then Largest Current element

The procedure FindMax implements the algorithmprocedure FindMax (Score : ScoreArray;

NoOfScores : integer;

var HighScore : ScoreType);

var i : integer;

begin

HighScore := Score[ i ];

for i := 2 to NoOfScores do

if Score[ i ] > HighScore

then HighScore := Score[ i ]

end;

3.5. Searching an array for a target value e.g., we want to find out whether a certain person is a

member of the Computer Club. procedure Searching (Name : NameArray;

Target : NameType;

var Position : integer);

var i : integer;

begin

Position := 0;

for i := 1 to MaxSize do

if Target = Name[ i ]

then Position := i ;

end;......

if Position > 0

then writeln (Target, ‘ is found in position ‘, i);

else writeln (Target, ‘is not found.’)

3.6. Copying an array

if two arrays are declared the same array type, the contents of one array can be copied to the other array.

declaration:cont MaxNo = 10;

type NumArray = array[1..MaxNo] of integer;

var A, B : NumArray;

C : array[1..MaxNo] of integer; assignment statement:

for i := 1 to MaxNo do

A[ i ] := B[ i ];

4. Parallel Arrays a data collection often contains items of different types.

E.g. , the data representing the performance of a class of students may consists of the student’s names, their exam scores and their grades.

to store these data, we can declare separate arrays with identical index type for names, scores and grades, as follows:const MaxNo = 40;

type NameArray = array[1..MaxNo] of string;

ScoreArray = array[1..MaxNo] of real;

GradeArray = array[1..MaxNo] of char;

var Name : NameArray;

Score : ScoreArray;

Grade : GradeArray;

These 3 arrays are called parallel arrays.All data items with the same index belongs to a particular student.

4. [Cont’d]

In the figure, related data items are with the same index 1 2 3

Name Chan Tai Wai Cheung Man Ying Chung Chi Ming

1 2 3Score 89.5 65.2 90.2

1 2 3Grade A C B

Example : write a program segment to display the name, the score and the grade of the student who is first in class.

4. [Cont’d]

steps: 1. find the index of the highest score2. print out the name, the score and the grade with this

particular indexprocedure FindMaxIndex (Score : MarkArray;

var HighIndex : integer); .......

var i : integer; {Main Program}

begin FindMaxIndex(Score, HighIndex)

HighIndex := 1 ; writeln(‘The student first in class is’,

for i := 2 to MaxNo do Name[HighIndex]);

if Score[ i ] > Score[HighIndex] writeln(‘The score obtained is ‘,

then HighIndex := i ; Score[HighIndex]);

end; Grade[HighIndex]);

......

5. Two-dimensional Array

can be used to handle data represented in tabular formarray [row index, column index] of base typee.g., type TableType = array[1..3, 1..5] of integer;

var Table : TableType;

represent a 3 by 5 table which can be pictured as follows:1 2 3 4 5

123

What metaphor can you think of to What metaphor can you think of to represent this?represent this?

5. Two-dimensional Array

can be used to handle data represented in tabular form

Block A

Block B

Block C

Block D

Block E

3A

2A

1A

3B

2B

1B

3C

2C

1C

3D

2D

1D

3E

2E

1E

3/F

2/F

1/F

Layout of Purple Layout of Purple HouseHouse

5. [Cont’d]

ExampleDeclare a two-dimensional array and write a program segment to generate the contents of the following table:

1

2

3

4

2

4

6

8

3

6

9

12

4

8

12

16

5

10

15

20

5. [Cont’d]

Declaration:type TableType = array[1..4, 1..5} of integer;

var Table : TableType;

Program Segment:for Row := 1 to 4 do

for Col := 1 to 5 do

Table[Row, Col] := Row * Col;

5. [Cont’d]

Declare a two-dimensional array to store the test scores for students in a class and write a procedure to calculate the total score of each student and the mean score of each test. You can assume that there are 10 students with three scores each.

Student 1

Student 2

Student 3

Score

89

78

50

56

70

46

67

65

53

Student 9

Student 10

64

83

58

76

60

69

5. [Cont’d]

Declaration:type ScoreTable = array[1..110, 1..3] of integer;

MeanArray = array[1..3] of integer;

TotalArray = array[1..10] of integer;

var Score : ScoreTable;

{mean score of each test}

TestMean : MeanArray;

{total score of each student}

TotalScore : TotalArray;

5. [Cont’d] The procedure that processes the

scores:procedure ProcessScores (Score : ScoreTable;

var TestMean : MeanArray;

var TotalScore : Total Array);

var Student, Test, Sum : integer;

begin

{Find the sum of each row}

for Student := 1 to 10 do

begin

TotalScore[Student] := 0;

for Test := 1 to 3 do

TotalScore[Student] := TotalScore[Student]

+ Score[Student, Test];

end;

{Finding the sum of each column and then the mean}

for Test := 1 to 3 do

begin

Sum := 0

for Student := 1 to 10 do

Sum := /sum + Score[Student, Test];

TestMean[Test] := trunc(Sum / 10)

end

end;

6. Arrays as Parameters The procedures headings in Section 3:

procedure FindMax (Score : ScoreArray;

NoOfScore : integer;

var HighScore : ScoreType);

procedure Searching (Name : NameArray;

Target : NameType;

var Position : integer);

6. Arrays as Parameters The procedures headings in Section 3:

procedure FindMax (Score : ScoreArray;

NoOfScore : integer;

var HighScore : ScoreType);

procedure Searching (Name : NameArray;

Target : NameType;

var Position : integer);

The modified procedure headings:procedure FindMax(var Score : ScoreArray;

NoOfScores : integer;

var HighScore : ScoreType);

procedure Searching (var Name : NameArray;

Target : NameType;

var Position : integer);


Top Related