Professional Documents
Culture Documents
Arrays 1D
Arrays 1D
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
• 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>
FOR Count 1 TO 5
INPUT StudName
StudentsList[count] StudName
NEXT
• You can declare arrays by placing the values directly into them.
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