Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

Arrays

Data structure
What is an array?
• An array is a data structure that stores multiple elements (values) of the
same data type within a single variable.
• An array is a static data structure. This means the array is declared with a
specified number of elements of one specified data type and this does not
change after compilation.
Difference between an array and a variable
• A variable can only hold one data value whereas an array can hold
multiple values.
Example
If you want to store 25 student names you would be required to declare 25
variables while using an array you could store all 25 values in a single array
set up to accept 25 data items.
Types of arrays
• One Dimensional
• Two Dimensional
One Dimensional Array

Actual representation in coding


Conceptional representation

• Index numbers are sequential and in VB the numbering starts from zero
• The first element in the array has index value 0, the second has index 1
How to declare an array
DECLARE <array identifier> : ARRAY[<lowerBound>:<upperBound>] OF <dataType>

• Give an array name and allocate appropriate data type


• Define the size of an array which will be determined by
the number of data items that the array is required to hold
Enter data into an array
DECLARE StudentsList: ARRAY[1:5] OF STRING
DECLARE StudName: STRING

FOR Count  1 TO 5
INPUT StudName
StudentsList[count] StudName
NEXT

• You can declare arrays by placing the values directly into them.

DECLARE StudentsList: ARRAY[1:5] OF STRING = (“Tom”,”Mary”,”John”,”Sam”,”Sue”)


Display data into an array

FOR Count  1 TO 10
PRINT StudentsList[count]
NEXT
1D Array Tasks
1. Declare an array listing 5 animals in a game park (lion,
Cheetah, Zebra, Giraffe, elephant)
2. Write code to output the first and last animals
3. Someone has accidentally eaten the Zebra, let the user add
a new third animal rhino and print them all out:
4. Write a loop so that you can input each of your five best
friends and it will output them in the order you input them.
ANSWERS
1. DECLARE Animals: ARRAY[1:5] OF STRING = (“lion”, “Cheetah”, “Zebra”, “Giraffe”,” elephant”)
2. PRINT Animals[1]
PRINT Animals[5]
3. a) Animals[3]= “Rhino”
b) FOR Count  1 TO 5
PRINT Animals[count]
NEXT
4. DECLARE BestFriends: ARRAY[1:5] OF STRING
DECLARE FName : STRING
//enter names
FOR Count  1 TO 5
INPUT FName
BestFriends[count] FName
NEXT
// display names
FOR Count  1 TO 10
PRINT BestFriends[count]
NEXT

You might also like