0% found this document useful (0 votes)
11 views25 pages

Gr11IT Delphi Chapter7 Arrays

Chapter 7 discusses arrays as a fundamental data structure in programming, specifically in Delphi. It explains how arrays store multiple values of the same data type under a single name and how to declare and manipulate them. The chapter also covers the importance of assigning values to arrays and the use of assignment statements for initialization.

Uploaded by

chaundreventercv
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)
11 views25 pages

Gr11IT Delphi Chapter7 Arrays

Chapter 7 discusses arrays as a fundamental data structure in programming, specifically in Delphi. It explains how arrays store multiple values of the same data type under a single name and how to declare and manipulate them. The chapter also covers the importance of assigning values to arrays and the use of assignment statements for initialization.

Uploaded by

chaundreventercv
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/ 25

Module

Chapter 7
Arrays

162 Chapter 7: Arrays


Chapter
Arrays 7

Introduction
All programming languages have structures
available to store data in numbered lists. A data structure refers to the way
data is organized. An example of
These numbered lists keep data in memory
a data structure we have already
while a program is running. The program can
    
manipulate and refer to the data again and
again when required.
In Scratch the data structure used to store a list of values is called a List.

Numbered lists in Delphi components


You have used the Memo, RichEdit and RadioGroup components in your Delphi
programs before. Each of these components has a property which can be used to
temporarily keep a list of string values. It is called the Lines property for the Memo
and RichEdit , and the Items property for the RadioGroup.

You will recall from work we did in Chapter 4 that the string values in the Items
     !"#  
$ !!% !&  '()      *+%- $ !!% !&  '/()   
  *+0 -$ !!% !&  '1()      *+2-
#   *   2   0 ) 3   
same way.
&  5 2  '()      +//689;- 
5 2  '/()      +//<8=>- 

Chapter 7: Arrays 163


Module
%  *       ) )
components. In Delphi such a data structure is available and it is called an array. You
are going to learn how to create arrays and manipulate data in arrays.

Array as a data structure


6   )   )   *  ) "
containing values of the same data type.
The elements In Scratch the values we put
2   
?  @ the program itself is stored.
? are all stored under one name. When the program is opened
and executed at a later stage
An array is a temporary data structure which only
2   )
exists in primary memory. All the elements of the populated with the saved data
array are in primary memory simultaneously. It is and therefore the values will
created when the program is executed and ceases to appear in the list.
exist when the program is closed.

All elements in the array are of the


same data type&%) ) 
) *  B  
   " Name of the array.

arrNames
James Dean Samantha Kagiso
'/( '1( 'L( 'P( 'L(

IndicesF%@*    ))  


 B    

? #   *FH 
? An array can contain a number of values while a single variable can only contain
a single value.
? All the elements of an array must be of the same data type, for example all
strings or all integers.
? #       "
type such as Integer or Char. The numbers referring to the elements of an array
    )   HJ    )  
and String cannot be used as indices.
? K  ) )      
the index of the element in the array
& *H 'L(   Ld element in the array,
 ) )   *+% -  ) 
? K    J   )    
only one index value.

164 Chapter 7: Arrays


Declaration of an array

QU6HV8'2&X&(U< #VZ

Any suitable Assign a value to


 ) * the lower and upper Data type of values to
name. indices. be stored by the array
e.g. Integer, Real,
%   [  <

H   8
? ArrName is the name of the array.
? LowerIndex        
UpperIndex      
? LowerIndex and UpperIndex must be of an ordinal data type and are separated by
   "
? UpperIndex must always be larger than LowerIndex.
? <BaseType> refers to the data type of the array elements and can be any available
data type in Delphi.
2    )     *  )
be stored in these arrays.

var arrWeight : array[1..10] of real; var arrSymbols : array['A'.. 'F'] of integer;

arrWeight arrSymbols
1 88.5 A 10
2 120.8 B 5
3 65.6 C 12
… 55.0 D 7
9 73.8 E 5
10 66.9 F 6

var arrAnswer : array[10..20] of char; var arrTemp : array[-2..80] of integer;

arrAnswer arrTemp
10 C -2 12
11 D -1 8
12 A 0 4
… B …
19 B 79 45
20 C 80 22

Chapter 7: Arrays 165


Populating an array
Module
Space is reserved in memory for each element of the array when the array is declared.

&\      *    ) 


private variable of the class of the Form. For example all the elements of the array declared
  *  )   *  *     "
All the elements of the array declared to keep string values will contain the value null
  *    "^*      *  
yourself, and not depend on the programming language to do so. Other programming
     *   ) )  * * ) 
6 + ) - *   *  
K  )  * ) )  * 
"  * not   

The actual values you want the array to store are assigned to the array elements by
    ) & )*      
 B  ) *  

Use of assignment statements


Assignment statements can be used when
? the programmer knows in advance which values need to be assigned to the array
? there are only a few elements required to be in the array
? the contents of the array will probably not change.
X *     *     )
in another event handler manipulates the values. In the next example a program has to
)  * !     $) 
used to assign the prizes to the elements of the array.
H5#38#     *  "  
we need to declare the array with class scope.

private arrPrizes is declared in the private


arrPrizes : array[1..5] of string; ) j   )  )"

procedure TfrmCompetition.FormActivate(Sender: TObject);


begin
arrPrizes[1] := 'Justin Bieber concert tickets';
arrPrizes[2] := 'iPad';
arrPrizes[3] := '8 GB Flash disk'; arrPrizes can be accessed
arrPrizes[4] := 'Chocolate gift pack'; by all methods in the
arrPrizes[5] := 'R5000 clothing voucher'; unit.
end;

procedure TfrmCompetition.ButtonWinClick(Sender: TObject);


begin
Showmessage(arrPrizes[Random(5)+1]);
end;

166 Chapter 7: Arrays


Another way of assigning values to an array is using a loop. For example:
for i := 1 to 10 do
arrNumbers[i] := Random(50) ;
The index of an element can be used to refer to an element in a programming
statement. For example:
rPrice := arrPizza[3] + 12.50 ;
& )      6
)  )) )     @j8
for i := 1 to 10 do
begin
arrPrice[i] := arrPrice[i] * 1.1 ; //increase each value in the array by 10%
//display the value in a RichEdit
redOut.Lines.Add(FloatToStrF(arrPrice[i], ffCurrency, 10, 2)) ;
end ;

Activity 1: Assign values to array elements

/ 6    ) )


where listeners must phone in and choose
/ 93) 
   B  !K  
listener phones in and chooses a number,
the announcer enters the number and
the prize allocated to the number appears
on the screen. Write the program the
announcer can use. An example of the
program interface is displayed here.

#   ))* // * 


with the data for the book. Open the
program and complete the code in the
event handlers.

1 5   )* //[    


)   //6[ )<
jK  [ )< )     
doubled.

Assign values as part of the declaration of the array


%   *))  )   *    
of months or the days in a week. This is when a constant array becomes useful. The
const)   begin of the procedure where you want to use
the array.

Chapter 7: Arrays 167


Module %  )  *  )   ) 
and an equal sign.

const
arrMonthName : array[1..12] of string = ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October',
'November', 'December');
var
iCount : integer;
sAllTheMonths : string;

begin
sAllTheMonths := ''; //Initialise the string to an empty string
Randomize;
//Add each month and an <enter> character to the string
for iCount := 1 to 12 do
sAllTheMonths := sAllTheMonths + #13 + (arrMonthName[icount]);
ShowMessage(sAllTheMonths);
end;

We can adjust our prizes example program by using a constant array. In this case the
array can be declared as follows:
implementation The array has unit scope to allow the code of
{$R *.dfm} more than one event handler to refer to the
const values in the array.
arrPrizes : array[1..5] of string
=('Justin Bieber concert tickets', 'iPad', '8 GB Flash disk', 'Chocolate gift pack',
'R5000 clothing voucher');

Activity 2: Make use of constant arrays

/ K  )        *    ) 3 


/ ># 
user must use a SpinEdit %   ) )  )  % 3 8
to choose the number of
0 Q8/
the movie he/she wishes
to watch. The name of the 0Q8>
movie must be displayed in EditorEnabled: False
the second RichEdit when In this way the user will not be able to enter
 ) )  '6( any invalid numbers outside the range of
<} />  )"H 8&  
Make use of a constant important to ensure that programming code
array to store the names does not refer to elements outside that range
 *  ~) of the indices of the an array as it will cause an
)  *  " +&5 5< -F)
that occurs when working with arrays.

168 Chapter 7: Arrays


Design an interface based on the following example and complete the program.

#   )   )*  


available with the data for the book.
Open the programs and complete the
code in the event handlers.

1 [  name, surname, animal, town6} 


 } )5)   €    
}6     @ )    
       ) ) }# 
 )))         K   
)   ) }       )  
} ) \  8
 %*  }    )  } +-+‚- +~-+ƒ-" 
\ '%) }(<} jK   ) ) 
'%) }(<}    )  ) 
 }       } 
)# )     }  
Challenge: X  #    B }*  
 #     B    *  
    ) }   )„

Populate an array with input from the user


6   *         
  )*  K     *  
entered can either be known or in many instances not known.
& *     )+ )- 
   @      * j8
ShowMessage('      ');
for k := 1 to 12 do
arrRainFall[k] := StrToFloat( InputBox('Rainfall for the previous year',
'Enter rainfall for month ' + IntToStr(k), '')) ;
? # 06#^X )   )   )   
with an array.
? #  ) )))     *))   
elements of type double as an argument, e.g.:
arrScores: array[1..7] of double ;

Chapter 7: Arrays 169


Module Example of code  
rAvg := mean(arrScores) ; Calculates the average of all the
elements in the array. In this case the
average of 7 elements.
rTotal := sum(arrScores) ; Adds up the values of all the elements
in the array.
rLargest := maxvalue(arrScores) ; Determines the largest value stored in
the array.
rSmallest := minvalue(arrScores) ; Determines the smallest value stored
in the array.
for k := low(arrScores) to high(arrScores) do The low)     
index of the array, and high returns the
highest index.

        

/ K  ))     


number of calories a person will burn per week if a
treadmill is used at the gym. The person has to enter the
number of minutes spent on the treadmill every day of
the week. The level of intensity should then be indicated
   *      
 "#    *)  
burnt per hour are as follows:

2    Medium intensity ^     


/1 /= 1

Display the number of calories the person


burnt every day of the week, as well as the The interfaces for these
total burnt for the week. )*  *  
the data for the book. Open
1 #  )     / the programs and complete
boys will compete in a tennis match as part of the code in the event
the fun events. They have to be divided into handlers.
two teams.
Write a Delphi program that will enter the
    )     6 
    ) % 3 "  
/ /&    *    * * 
     )    6    *  
      )    < * )* 
Display the names of the two teams with appropriate headings in separate
RichEdits.

170 Chapter 7: Arrays


L & ) )  )  ) J   )
Seven judges submit their scores. The highest and the lowest scores are
 ) *    )  ) 
)"       )
E.g. If the 7 scores are:
=>>9 9 9 9 > 
#  } )    ) "F  ) => >
The following marks remain:
>9 9 9 9 
The average is calculated as follows:
>9† 9† 9† 9† "€9‡ 1
Write a program to do the following:
? Read in the 7 scores into array.
? Display the two discarded values.
? Display the remaining list of values.
? [)    )

P K        /1  *   


named arrRain#         / L"
)  /1  
 #   +  !  -     
  /1 #   
should look something like this:
‚‚‚‚    
0 /8 ‚‚‚‚‚‚‚ = month.
0 18 ‚‚‚‚‚‚ ;
^  8X   J
0 L8 ‚‚‚‚‚‚‚‚‚ 
handling to build an output string
.................................
for each month.
0 /18 ‚‚‚‚‚‚‚ =

&  )     )  


values the user has to enter into an array. The programmer can ask the user to
indicate how many values will be entered.
For example when a program has to calculate the average mark for a class test, the
      )     )  )) )    B 
number of learners. The loop for entering the marks will be repeated based on the
number the user entered. For these types of programs, the programmer should:
? declare an array large enough for the maximum
number of elements ever to be saved in the array. Rather declare an array
& ) '/P(     with too many elements
   P*  * *  than with too few.
  * 
P  ) "
? ensure that the user is not able to enter more values than what was provided for
 ) 

Chapter 7: Arrays 171


Module
2    ) ))  
elements a user enters:
A constant can be used to indicate how many elements an array consist of.

unit frmClassMarks_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
const
MAXNUM = 10;
type &  )    
TfrmMarks = class(TForm) class, the constant value has to be declared
private in the interface of the unit above the class
arrNames : [1..MAXNUM] of string;  # )     )
public +*- )    
end; value will be used.

The number of elements that is read into the array can then be controlled through
program code using the constant value.

repeat
iNumNames := StrToInt(InputBox('Enter names','How many names ? Maximum is ' +
IntToStr(MAXNUM),IntToStr(MAXNUM)));
until iNumNames <= MAXNUM ;

Verify that the user enters a number less or equal to


the maximum number of elements in the array.

H   )   


same as the number of elements in the array.
for k := 1 to iNumNames do
arrNames[k] := InputBox('Enter names', Enter name number + StrToInt(k), '') ;

X )      *  8


? The number of elements in the array is clearly documented in the code.
? The programmer does not need to remember how many elements the array
consists of, but only uses the name of the constant when referring to the
number of elements.
? If the number of elements in the array has to change, it only needs to be
changed where the constant is declared and nowhere else in the program
code.

172 Chapter 7: Arrays


Activity 4: Review an error when entering values into an array

Open the program frmClassMarks_p provided with the data for this chapter. The
number of names to be entered has not been validated in this program. Execute
the program and enter a number that is bigger than the number of elements the
array can keep.
" \  )      
than the maximum number of values declared in the array?
" 6     )  Š
)" K     Š
" K        Š
" 6)        )  )
* ))   ) 

In the previous example the user had to enter


the number of values to be entered. The
)  }     
*) )<} 
able to add the next name. The program has to
keep track of the number of names that were
entered to ensure that the number of elements
the array can keep is not exceeded.

private Declare the array and a


arrNames : array [1..MAXNUM] of string; counter with class scope.
iCount : integer;

procedure TfrmNames.FormActivate(Sender: TObject);


begin
iCount := 0; &  !)   
end; j )* 

procedure TfrmNames.btnAddNameClick(Sender: TObject);


begin
K   ) )  <} 
if iCount < MAXNUM then
"         
begin
elements allowed in the array will not be exceeded.
Inc(iCount);
arrNames[iCount] := InputBox('Enter the name','Name:','');
end
else Display an error message if
ShowMessage('Number of names exceeded');  +-
end;

Chapter 7: Arrays 173


Module      

/ # \  3)@      ) /1


 -‹       )  Œ) 
 #   /1   ) ) Œ) 
    0*  L
 #       -  
 #      *  L
 &9 9/1    )   ) Œ) 
  -‹    
 & 9    Œ) 9
names must be selected as follows: The interfaces for these
 \    9) *  )*  * 
   &   L with the data for the book.
for example, then every third learner must be Open the programs and
selected. complete the code in the
 38 /=   ) ) event handlers.
subject
 /=9‡L
 #   )  8L ;  /1 /9    
Display the selected names in a RichEdit with an appropriate heading.

1 #  * *     ))


 )   )  ) ) 3*       
 * *    
 )  #   * %\"
number of values is as follows:
For each element:
? Subtract the average from the element.
? j   @  B)

M is the average of all the values.


    *  )   *  
calculated.
Create a program that will read a number of values and calculate the standard
*   * 1)  "0*  
L*   ^*       L* 
The program should keep track of the number of values entered, and ensure no
 L) 
 ~)     * 8/Z ;Z PZ 1Z Z>
# %\ ;11

174 Chapter 7: Arrays


Read data from a text file
When working with large volumes of data or when we are busy with the development
    ))       
) )  &      )  
    $*   )    )  
  )    #    
        *   
K      
? count how many items are read into the array
?          )  ! 
array.
&   )     6
 19    5)     )
be manipulated, e.g. a random name can be chosen as the winner of a prize, you can
)        ) )    )
be sorted, etc..

const
MAXNAMES = 25;
Decide on the maximum number of elements the
 )    ) ) )
type
frmChooseWinner = class(Tform)
...
private
arrNames : array[1.. MAXNAMES] of string;
iCountNames : integer;
end;
Declare the array and a counter with class scope.

procedure TFrmWinner.btnReadAndDisplayClick(Sender: TObject);


var
tNames : TextFile;
iCounter : integer;
begin
AssignFile(tNames, 'Classlist.txt');
Try
Reset(tNames); # )  35j  
Except  ) 6H\ ) 
ShowMessage('File does not exist'); is less than the number of elements
Exit; declared for the array.
End;

while (NOT Eof(tNames)) AND (iCountNames < MAXNAMES) do


begin
inc(iCountNames);
readln(tNames, arrNames[iCountNames]);
end ; Display all the names saved in the
 jJ# ) 
for iCounter := 1 to iCountNames do
contains the actual number of
redOutput.Lines.Add(arrNames[iCounter]);
values saved in the array.
end;

Chapter 7: Arrays 175


Module ? <)    ) )   19  
    19 *    

? Ž     )  19   # * 
iCounter will contain the actual number of values saved in the array.

    

/ 6J) )  $  


 //&#) 3      //&#) 
    *  //       
#    19   *
   *  2  )  
the array randomly. That person wins the iPad.
 $  <}  j '\ ('\  
K (# '\  K (<} $   
  )* )  * 
  # '\ (<} + -)  
*    

1 $ )     }     ) 
   )  )  6   ) 
 )  )  ) ) \   ) 
code to do the following:
? [   )     *    ) 
products.
?  *      
? Display the values in an appropriate output component.
? 3   )  )  )  *  
increase.
? Increase all the values in the array with the percentage that has been
entered.
? Display the increased values in an appropriate output component.

L 2  )   )     ) 
<)        ) )    ) 
program to display the names of the learners in a random sequence.
Design an interface and write code to do the following:
? /     
? Display the names in a random sequence in an appropriate output
) # )  }  )     
will appear twice.

176 Chapter 7: Arrays


Hint: X  )  / /X 
the number to display the name with the corresponding index in the array.
3)         & - 
             
displayed again and a new number must be generated.

P 6 )     *     )   


6 @   *       
lowest and average of the values. It must also display how many of the values
were higher than the average.
   * "  *  
3    "  6       
/*     \ ))      
appropriate output component.
Error Control :   ) )   )   
make sure no more values are read than the space provided for in the array.

9 2  *  )  )     ) # /
@  )  6 < [\    K    
 )) }) @ " *  
6   "  
 #   -       
by the learner and test the answers against the memorandum. Hint8X  
X[ )  *    ) } 
 [)  - *   * 
appropriate output component.
 6'  (<} ))     -  )
be entered.
Challenge80   J   
Examples:
? The user must be able to enter the memorandum only once.
? It must be possible to enter the name of the learner only once the
memorandum has been entered.
? # -     ) -   
been entered.

Use specific indices


6   * }  
? *  *  @)     
?           }
F           *  *   
)  
^*  -       8
# /)        )3) )   
 @) 0   )*   
%0%)    )   * )  

Chapter 7: Arrays 177


Module
&    )  *  ) ) )    
the winner, the following applies:
? An array will be used to keep record of the number of votes cast for each
)  
? #   )    )    
* ) ) F *  ) )  /  *
      *  ) )  1 
 1  )
? The votes are not necessary entered in sequence according to the elements of the
F     * ) )  P   )* 
)  /  )
? Some elements of the array may never receive a value e.g. nobody voted for
)  9
For such a program the programmer needs to ensure that all the values of the array
    !)   

! " # $  

/ 6  ;) 


perfume. The manager would like to know The interfaces for these
how popular each of the perfumes is with )*  *  
customers. A computer program is required the data for the book. Open
the programs and complete
that allows customers to choose the most
the code in the event
popular perfume. The program must be able handlers.
    *) 
basis.
Write a program to do the following:
? $*   )         B * 
perfumes.
? Keep record of how many customers voted for each perfume so far.
? Display the total number of votes for each perfume in an appropriate output
component.
The following is an example of the interface and output:

178 Chapter 7: Arrays


Note:
 # & &    )  * 9# 
*  "6  ))    
containing the number of votes should be declared. The array can be declared
in one of two possible ways:

var var
arrVotes : array[0..5] of integer; arrVotes : array[1..6] of integer;

The following code will increase the value of the perfume voted for:

iVoted := rgpPerfume.ItemIndex; iVoted := rgpPerfume.ItemIndex+1;


inc(arrVotes[iVoted]); inc(arrVotes[iVoted]);
In this case the index of the element in the
array is always one more than the index of the
corresponding element in the Radio Group.

Complete the program, save and execute it.

1 #   *))   ) 


candidates must be elected as president. Each teacher sends a summary of
the number of votes cast by his/her register class for each candidate. Write a
program that will enable the
) )    
votes cast for each candidate.
An example of the interface is
displayed here:
? # *  
;"    % 
3  )  - 
# )  
) )  '6(<}
below the corresponding
SpinEdit. The number of
votes obtained by the
candidate is then increased
by the number entered in
the SpinEdit.
? 5) *   *   ) ) )  'K (
<}  )     *    
? # '  (<}    *    ) 
)   ) ) # <})  ) 
*   J) 

Chapter 7: Arrays 179


Module
In some instances it is meaningful to make use of characters as indices rather than
integer numbers. For example: In a program where we enable the user to look up words
 H6#5 )  )))       
)    *  }  
  +6- +<-  )"   ) #   )  # H6#5 )    
    ) )   }  
}       6  }‘‘ 
user is the index of the array containing the <* }‘‘  )

arrPhoneticAlph: array ['A'.. 'Z'] of string = ('Alpha', ' Bravo', 'Charlie'...... 'Yankee', 'Zulu' );

arrPhoneticAlph
A Alpha
& )  ) )  "
B Bravo
C Charlie
...
Y Yankee
Z Zulu

% " #    

/ K    


the program described in the #   )   )*  
*  H6#5 ) available with the data for the book. Open
  "6     the programs and complete the code in the
event handlers.
}   ) )
'2X(<} 
)   )  # ) H6#5
 )          )* "3
 ) ) ) }  
)*   )   

1 K  


the following: Even though schools use a number system to rate
) *        
? Allow the user to    )   @ 
enter the marks      ) # 
obtained by learners grading scale for symbols is as follows:
in a test. >F/86
? Determine and =F= 8<
display the symbol ;F; 8[
 )  9F9 8\
mark. PFP 83
<P8j

180 Chapter 7: Arrays


? \   6- <-  )      
of the symbols once all the marks have been entered.
 H   8
The indices         B 
symbols. The array can be declared as follows:
var
arrCountSymbols : array['A'..'F'] of integer;

Find an element in an array


& *  )*      )    
^*   )      )   j
the names of learners in a class or a list of videos available at a video shop. These
* )   K   ) ) 
    )        & ) 
*)            
last element of the array is reached. In programming terms we refer to this process as
     .

H 8#      )        6


search process should always stop as soon as the element has been found. It is a poor
  )   ) )      
&   )           
*  ) )   /   ) )  *
   ) „

Chapter 7: Arrays 181


Module
&   <*(Found)    +-   ) 
whether the element has been found or not.
TASK: Find a certain word in an array of words
<3&H
 6 +K )   Š-
Get SearchString
 j‡ 
 [ ‡H*   
 އ/
  j H5# "6H\ŽU‡[ "
   %  '[ (‡%) %   
   j‡ 
   އކ/Z
endWhile
if Found is true then
  \ %) %  †' was found'
else
  \ %) %  †' was not found'
endIf
3H\

& '   # ()

/ K   )  


assist with enquiries at a video shop. The #   )   )*  
program must read the available videos are available with the data for
the book. Open the programs
    #  
and complete the code in the
the video a customer wants to rent should
event handlers.
be entered. The program should then use
a linear search method to search for the
   #        )
    ) )*   0    videos.txt
supplied with the data for this chapter.

1 6    


)Names.txt# 
is available with the data for
)* K 
which will read the names
      
and then allow the user to:
? display all the names,
?   )))
 ) )

182 Chapter 7: Arrays


? enter part of a name, and display all
 )     } 
example:
 K     <}
'2  ( )* 5)
the names have been read into the array, the
 <}  )*   '2  (<} 
) )*

Activity 10: Written questions on arrays

/ #  @      


by the diagram: X
" K     Š 1 3
" ^    *Š 2 54

)" 2    )    ) " 3 49
4 16
" K  ) 
5 11

1 %  H )    *  


displayed in the diagram:
What will the value of the fourth element of the array
arrNumbers
)   )) Š
" arrNumbers[4] := arrNumbers[3] + arrNumbers[5]; 1 12
2 34
" arrNumbers[4] := arrNumbers[3+5];
3 46
)" iPlace := 5;
4 56
arrNumbers[4] := arrNumbers[iPlace];
5 12
" iPlace := 5; 6 37
arrNumbers[4] := iPlace; 7 78
8 89
L *8
9 19
var
10 34
arrFirst, arrSecond : array[1..5] of real;
arrThird : array['A'..'J'] of integer;
arrFourth : array['a'..'j'] of char;
k : char;
x : integer;
State whether the following statements are valid or not with reference to the
*) & *    
" arrFourth['k'] := '*' ; " arrFirst[2*4] := arrSecond [2];
)" arrThird[k] := 12; " arrFourth[x] := 'A';
" arrThird[k] := 'B'; " arrFirst[x] := arrThird[k];
" arrFourth['a'] := 'J' ; " arrFirst[4+1] := arrFirst[4] + 1;
" arrThird[k] := TRUE; Œ" arrFirst[x] := 12/4;

Chapter 7: Arrays 183


Module 4. Indicate in each of the following incidents if an array as data structure is
necessary or not.
" [)        
" \  *      *  
)" %    )
" \    )  *     
" \          ) )*

9 %           8


"6  )    ) ) *
" 6 )   )  *)
)" 6 6")   <" 
assignment statement:
A := B;
" 6 )   * 

; %  )      @  8


var
arrNumbers: array[1..15] of integer;
iCount : integer;
iX, iY : integer;
begin
iX := 1;
for iCount := 1 to 15 do
begin
if arrNumbers[iCount] > arrNumbers[iX] then
begin
iX := iCount;
iY := arrNumbers[iX];
end;
end;
end;
The code must determine which element in the array is the smallest.
" K     )  *    ‚ ~Š
" #          3  
 )           
array.
)" &  B)*  * [   /Š0*  
" K     )    *    
in the array in a RichEdit.

= [   ) )8


var
arrNumbers : array['A'..'G'] of integer;
cLet : char;
iCount : integer;

184 Chapter 7: Arrays


begin
cLet := 'A';
for iCount := 1 to 7 do
begin
The succ)   *   
arrNumbers[cLet] := iCount;
on the value supplied as the argument.
cLet := succ(cLet);
end;
for cLet := 'G' downto 'B' do {1} The pred)   
value that comes before the value
arrNumbers[cLet] := arrNumbers[pred(cLet)];
supplied as the argument.
for cLet := 'A' to 'G' do
redOutput.Lines.Add(IntToStr(arrNumbers[cLet]));
end;
" \    )    )  )    
H )  
" K       ) 3  *   ) Š
)" K       ) 3     ’/“ )  
for cLet := 'B' to 'G' do
" K )         * Š[  
invalid statements so that they become valid.
arrNumbers[A] := 10;
arrNumbers[4] := 'G';
arrNumbers := 20;
arrNumbers[chr(66)] := 12;

> 6       ))     )  }


to create a password. The code must do the following:
Enter a string from the keyboard.
 %   ) )            )
last in the second element, etc.
Example:
 &   8\32$^&  %8&^$23\

 # )  } )  *     


correctly. Determine what the error is and explain how to correct it.

private
arr Password : array[1..10] of char; Array with class scope.

var
sInString : string;
iLast, iCount : integer;
Code in event handler.
begin
sInString := edtRead.Text;
iLast := length(sInString);
for iCount := 1 to iLast do
arrPassword [iCount] := sInString[iLast];
end;

Chapter 7: Arrays 185


Module  #   ) \   
)2}  )  )   }   
of the alphabet in reversed order. Complete the 1 Z
       2 Y
  " " 3 X
...
Event handler
24 C
var
25 B
M : integer;
26 A
arrLetters : ……(a) ……..;
K : ……(b) ……...;
begin
M := …….(c) ……;
for K := ……(d)….. downto ……(e)…… do
begin
…..(f)……...:= K;
M := M + 1;
end;
end;

Important terms and concepts


Array 6   )   )   *  )
 ")   *     

Constant array 6 )   *       )


statement.

Data structure A data structure refers to the way data is organized.

Element One of the variable values in an array which can be accessed by giving the
name of the array followed by the index of the element.

Enumerated data type An ordinal data type such as Integer or Char.

Flag 6*     )   )     &
 ) )    )      
not.

Index (singular) 6 *  )      


Indices (plural)

Linear search 6 ) )        )   @


through the list of elements.

One-dimensional array 6  ) )   *   " ) 
element can be accessed individually using a single index value.

186 Chapter 7: Arrays

You might also like