0% found this document useful (0 votes)
26 views47 pages

Introduction To Arrays - 2021

The document discusses using one-dimensional and two-dimensional arrays in Visual Basic, including how to declare, populate, reference, and manipulate array elements. Examples are provided to demonstrate creating arrays from data, accessing values based on indexes, and performing computations like finding averages using element values stored in arrays. The objectives cover creating, manipulating, and performing operations on one-dimensional and parallel arrays through techniques like looping and indexing.

Uploaded by

David Tawiah
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)
26 views47 pages

Introduction To Arrays - 2021

The document discusses using one-dimensional and two-dimensional arrays in Visual Basic, including how to declare, populate, reference, and manipulate array elements. Examples are provided to demonstrate creating arrays from data, accessing values based on indexes, and performing computations like finding averages using element values stored in arrays. The objectives cover creating, manipulating, and performing operations on one-dimensional and parallel arrays through techniques like looping and indexing.

Uploaded by

David Tawiah
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/ 47

CICS 313:

Visual Basic Programming

Arrays
Ghana Technology University College
Lecturer – Dr. Forgor Lempogo
2021
Objectives
 At the end of this lesson, you should be able to:
 Create and manipulate a one-dimensional array

 Code a loop using the For Each…Next statement

 Perform computations/operation (search, sort, traverse,


insert, remove, etc.) involving elements of one-dimensional
arrays
 Create and manipulate parallel one-dimensional arrays

 Perform computations/operation (search, sort, traverse,


insert, remove, etc.) involving elements of parallel one-
dimensional arrays
 Create and manipulate a two-dimensional array

 Perform computations/operation (search, sort, traverse,


insert, remove, etc.) involving elements of two-dimensional
arrays
2 CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using Arrays
 Simple variable (or scalar variable): a variable that
is unrelated to any other variable in memory

 Array:
A group of variables with the same name and data type
that are related in some way
Used to temporarily store related data in memory
Increases the efficiency of a program

 Commonly used arrays:


One-dimensional
Two-dimensional

3 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


One-Dimensional Arrays
 One-dimensional array:
Can be viewed as a column of variables

 Subscript/Index:
A unique number that identifies each variable in arrays
Starts at 0 for first element in the array
Must be an integer

Element
Individual item in the array

 Use array name and subscript to refer to each individual


variable in the array
 Boundaries
 Lower Subscript, 0 by default
4
 Upper Subscript
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Two Ways to Declare Arrays
 Using upper bound versus assigned values

Dim ArrayName (UpperSubscript ) as Datatype


‘ In this case each element of the array will be assigned a default
‘value: numeric  0, string  “” (no characters)

Dim ArrayName ( ) as Datatype = {InitialValueList}


‘No upper Subscript is allowed
 Examples

Dim strName (3) as String ‘an array of 4 elements:


Dim decBalance(99) as Decimal ‘an array of 100 elements:

Dim strDept ( ) as String = {"ACT", "MKT", "HR", "MIS"}


Dim intActCode ( ) as Integer = {10, 20, 30, 40}

5
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Referencing Array Elements
Use the Index(s) of the Element

strName
strName(0) = "Ama Dela"
(0) Ama Dela
(1) Kwaku Menu strName(1) = "Kwaku Menu"
(2) John Mensah strName(2) = "John Mensah"
(3) Dela Kuma strName(3) = "Dela Kuma"

6
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Manipulating One-Dimensional Arrays
 Array elements can be used like any other variable

 Examples:
Display the contents of an array
Access an array element using its subscript
Search the array
Calculate the average of data stored in a numeric array
Find the highest value stored in an array
Update array elements
Sort array elements

7
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
A One-Dimensional Array - Example

Create a one dimensional


array, elements of which will be
the months of the year.

Elements of the array should


be displayed in a list box on
form load

A selected element in your


array should be displayed in a
label when a button is clicked

8
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
A One-Dimensional Array - Example
Private Sub MainForm_Load( ByVal sender As Object, ByVal e As System.EventArgs} Handles
Me.Load
‘Fill the list box with array values and the select the first item
Dim months () As String = { "JAN" , "FEB" , "MAR" , "APR" , "MAY" , "JUN" , “JUL ", “AUG" ,
"SEP“, “OCT" , "NOV" , "DEC”}
For subscript As Integer = 0 To 11
monthListBox.Items.Add(months(subscript))
Next subscript
monthListBox.Selectedindex = 0
End Sub

Private Sub displayButton Click(ByVal sender As Object, ByVal e As System.EventArgs)


Handles displayButton.Click
selecteditemLabel.Text = monthListBox.Selecteditem.ToString
End Sub
Private Sub rnonthListBox_SelectedValueChanged(ByVal sender As
Object, ByVal e As System.EventArgs) Handles rnonthListBox.SelectedValueChanged
selecteditemLabel.Text = String .Empty
End Sub
9
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The For Each…Next Statement
For Each…Next statement:
Used to code a loop which processes each
element in a group or array

Creates a variable used to represent each


item in the group or array

Data type of the element must match the


data type of the group

10
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The For Each…Next - Example
Syntax:
For Each element [As datatype] In group
[statements]
Next element
Examples:
For Each monthName As String In months
monthListBox.Items.Add(monthName)
Next monthName

displays the contents of the months array in the monthListBox


Dim monthName As String
For Each monthName In months
monthListBox.Items.Add(monthName)
Next monthNarne
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
11
One-Dimensional Array – Example 2
Code 1 2 3 4 5 6
Amount 25000 35000 55000 70000 80200 90500

 The table above represent a list of


salaries and their codes.

 Create an array with salary amount


being it elements

 When a use enters a salary code,


your program should output the
12 corresponding salary.
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
A One-Dimensional Array – Example 2
Private Sub displayButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles displayButton.Click
‘Displays the salary amount associated with salary code entered by the user
Dim salaries() As Integer = {25000, 35000, 55000, 70000, 80200, 90500}
Dim code As Integer, isConverted As Boolean
‘ use the salary code to display the appropriate salary amount from the array
isConverted = Integer.TryParse(codeTextBox.Text, code)
If isConverted Then
‘ verify that the salary code is valid
If code >= 1 AndAlso code <= 6 Then
salaryLabel.Text= salaries(code - 1).ToString( "C0" )
Else
MessageBox.Show( "Enter a code from 1 through 6.”, "XYZ corporation" ,
MessageBoxButtons.OK,MessageBoxicon.Information)
End If
Else
MessageBox.Show( "The salary code must be numeric." , "XYZ Corporation" ,
MessageBoxButtons.OK, MessageBoxicon.Information)
End If
codeTextBox.Focus()
13
End SubCICS 313: Visual Basic Programming - GTUC 2021 Delivery
A One-Dimensional Array – Example 2
Private Sub codeTextBox_Enter( ByVal sender As Object , ByVal e As
System.EventArgs) Handles codeTextBox.Enter

codeTextBox.SelectAll()

End Sub

Private Sub codeTextBox_TextChanged(ByVal sender As Object, ByVal e As


System.EventArgs) Handles

salaryLabel.Text = String.Empty

End Sub

14
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
One-Dimensional Array – Example 3
Agent Ama Ali John Abena Kofi
Amount 45000 35000 25000 60000 23000

 The table above represent a list of


sales values from five employees

 Create an array with Sales amount


being it elements

 When a use enters a sales Value,


your program should count and output
the number of employees whose
sales amounts are more than the
entered value.
15
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
A One-Dimensional Array – Example 3
Private Sub salesTextBox_Enter( ByVal sender As Object ,ByVal e As
Systern.EventArgs) Handles salesTextBox.Enter
salesTextBox.SelectAll()
End Sub
Private Sub salesTextBox_TextChanged( ByVal sender As Object ,ByVal e
As Systern.EventArgs) Handles salesTextBox.TextChanged
countLabel.Text = String.Empty
End Sub
Private Sub searchButton_Click( ByVal sender As Object, ByVal e As
Systern.EventArgs) Handles searchButton.Click
‘Search the arrays looking for values that are greater than
‘the value entered by the user
Dim sales() As Integer = {45000, 35000, 25000, 60000, 23000}
Dim counter, searchFor As Integer, isConverted As Boolean
isConverted = Integer.TryParse(salesTextBox.Text, searchFor)
‘[continue
16 on the next slide]
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
A One-Dimensional Array – Example 3
If isConverted Then
‘ search the array, updating the counter when the array
‘value is greater than the searchFor value
For Each salesAmount As Integer In sales
If salesAmount > searchFor Then
counter = counter + 1
End If
Next salesAmount
Else
MessageBox . Show( "The sales amount must be numeric." , “Kaba Ltd",
MessageBoxButtons.OK, MessageBoxicon.Inforrnation)
End If
‘display the counter value
countLabel .Text = Convert .ToString(counter)
salesTextBox.Focus()
End Sub
17
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
One-Dimensional Array – Example 4
Student Ama Ali John Abena Kofi
Scores 98 100 56 74 35

The table above represent a list


of test scores from students

Create an array with Test Scores


being it elements

Find the average of the test


scores
18
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
A One-Dimensional Array – Example 4
Private Sub calcButton_Click(ByVal sender As Object , ByVal e
As System.EventArgs) Handles calcButton.Click
' calculate and display the average test score
Dim scores() As Integer = {98, 100, 56, 74, 35}
Dim scoresAccumulator As Integer
Dim averageScore As Double
' accumulate scores
For Each score As Integer In scores
scoresAccumulator = scoresAccumulator + score
Next score
' calculate and display the average score
averageScore = scoresAccumulator / scores.Length
averageLabel.Text = Convert .ToString(averageScore)
19
End SubCICS 313: Visual Basic Programming - GTUC 2021 Delivery
Sorting the Data Stored in a
One-Dimensional Array
 Sorting: arranging data in a specific order
 Ascending: first element is smallest, last element is
largest
 Descending: first element is largest, last element is
smallest
 Array.Sort method:
 used to sort elements in a one-dimensional array in
ascending order
 Array.Reverse method:
 used after Array.Sort method to change to
descending order
20 CICS 313: Visual Basic Programming - GTUC 2021 Delivery
One-Dimensional Array – Example 5

 Create an array that will take


the ten regions of Ghana as
input from a user

 sort the array elements in


ascending order when a
button is clicked

 sort the array elements in


descending order when
another button is clicked

21
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
One-Dimensional Array – Example 5
Module Level Declarations
Private regionNames(9) As String

Add Button Click


For subscript As Integer = 0 To regionNames.Length - 1
RegionNames(subscript) = InputBox("Enter Region", _
"Region Names")
Next subscript

22
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
One-Dimensional Array – Example 5
Ascending Button Click
Array.Sort(regionNames)
lblRegion.Text = String.Empty
For Each name As String In regionNames
lblRegion.Text = lblRegion.Text & name & _
ControlChars.NewLine
Next name

Descending Button Click


Array.Sort(regionNames)
Array.Reverse(regionNames)
lblRegion.Text = String.Empty
For Each name As String In regionNames
lblRegion.Text = lblRegion.Text & name & ControlChars.NewLine
Next name
23
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
One-Dimensional Array – Example 5
 We can add a list box in place of the label and use the
AddRange property of the listbox.Items Method
Ascending Button Click
Array.Sort(regionNames)
lsbRegions.Items.Clear()
lsbRegions.Items.AddRange(regionName)

Descending Button Click


Array.Sort(regionNames)
Array.Reverse(regionNames)
lsbRegions.Items.Clear()
lsbRegions.Items.AddRange(regionName)
24
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
One-Dimensional Array – Example 5
 We can use the Insert property of the listbox.Items
Method to insert values at specific indexes of the listbox
Ascending Button Click
Array.Sort(regionNames)
lsbRegions.Items.Clear()
For i As Integer = 0 To array1.Length - 1
lsbRegions.Items.Insert(i, regionName(i))
Next
Descending Button Click
Array.Sort(regionNames)
Array.Reverse(regionNames)
lsbRegions.Items.Clear()
For i As Integer = 0 To array1.Length - 1
lsbRegions.Items.Insert(i, regionName(i))
Next
25
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Parallel One-Dimensional Arrays
Parallel arrays:
Two or more arrays whose elements are
related by their position in the arrays

26 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Parallel One-Dimensional Arrays (2)

27
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Parallel One-Dimensional Arrays Example

 Above are parallel one dimensional


arrays.
 One array made of o product ID
and the other-the corresponding
prices for the products

 When the user enters a Product ID,


the program should output the
corresponding Price.
28
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Dim ids() As String = {"BX35", "CR20", "FE15", "KW10", "MM67"}
Dim Price() As Integer = {13, 10, 12, 24, 4}
Dim SearchFor As String
Dim subscript As Integer
Dim isfound As Boolean
Dim foundpos As Integer
SearchFor = idTextBox.Text
For subscript = 0 To ids.Length - 1
If ids(subscript) = SearchFor Then
isfound = True
foundpos = subscript
Exit For
End If
Next
If isfound = True Then
priceLabel.Text = Price(foundpos).ToString("C0")
Else
MessageBox.Show("Invalid Product ID", "My Gift Shop", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
29
idTextBox.Focus() CICS 313: Visual Basic Programming - GTUC 2021
Delivery
One-Dimensional Array – Example 6
idTextBox_Enter Event
Private Sub idTextBox_Enter(ByVal sender As Object, ByVal e As
System.EventArgs) Handles idTextBox.Enter

idTextBox.SelectAll()

End Sub

idTextBox_TextChange Event
Private Sub idTextBox_TextChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles idTextBox.TextChanged

priceLabel.Text = String.Empty

End Sub
30
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Arrays Example 7
A Visual Basic Application that
will accept a list of students
and their marks as input using
parallel one dimensional
arrays.

Find and output the :


student with the highest mark
student with the lowest mark
 average class score

31 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Input the Elements–ADD Students and Marks

35
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Show the Best Student

37
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Show Last student

39
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
ReDim Statement
 After an array has been declared, its size (but not its type)
can be changed with a statement of the form:

ReDim arrayName(m)

 Where:
arrayName is the name of the already declared array
m is an Integer literal, variable, or expression.

 Note:
Since the type cannot be changed, there is no need for an
"As dataType" clause at the end of the ReDim statement
42
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
ReDim Statement - Shortcomings
It causes the array to lose its current contents.
 it resets all String values to “”
resets all numeric values to 0.

This situation can be remedied by following


ReDim with the word Preserve.

44
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
ReDim Preserve Statement
The general form:

ReDim Preserve arrayName(m)

if you make an array smaller than it was, data


in the eliminated elements will be lost..

 Examples
ReDim Preserve strDept(20)
ReDim Preserve decSale(6)
45
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Two-Dimensional Arrays
Two-dimensional array:
Resembles a table with rows and columns

Each element is identified by a unique


combination of two subscripts: (row, column)
Subscripts are zero-relative

46
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Two-Dimensional Arrays (2)

47 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Two-Dimensional Arrays (3)
 Two-dimensional array:
Declared with highest row subscript and highest column
subscript (zero-relative)

 Number of rows = highest row subscript + 1


 Number of columns = highest column subscript + 1
 Can specify initial values for array elements
 If no initial values are declared, array elements are
automatically initialized

48 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Declare a Two-Dimensional array
Syntax
Syntax - Version 1
{Dim I Private} arrayName(highestRowSubscript, highestColumnSubscript) As
datatype
Syntax - Version 2
{Dim I Private} arrayName(,) As datatype = {{initialValues}, ... {initialValues}}

Examples:
Dim cities(5 , 3) As String
 declares a six-row, four-column array named cities; each
element is automatically initialized using the keyword Nothing
Dim scores( , ) As Integer = {{ 75, 90} , {9 , 25} ,{23 , 56} ,{6 , 12}}

 declares and initializes a four-row, two-column array named


49 scores
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Store Data in a Two-Dimensional Array
Syntax
arrayname(rowSubscript, columnSubscript) = value

Examples:
cities(0, 0) - "Tamale"
cities(0, 1) - "Sunyani"
cities(0, 2) - "Techiman"
cities(0, 3) - "Accra"

 assigns the strings "Tamale", "Sunyani", "Techiman", and


"Accra" to the variables contained in the first row in the cities
array
50
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Store Data in a Two-Dimensional Array
Examples
For row As Integer = 0 To 3
For column As Integer = 0 To 1
scores(row, column) = 0
Next column
Next row

 ‘assigns the number zero to each variable in the scores array

For Each number As Integer In scores


number = 0
Next number
 assigns the number zero to each variable in the scores array
51
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Two-Dimensional Arrays Example

 Above is a two dimensional array.

 The first column is made of product


ID and the other-the corresponding
prices for the products

 When the user enters a Product ID,


the program should output the
corresponding Price.
52
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Click Event of the Display Price Button
‘display the price associated with the product ID entered oy the user
Dim products(,) As String = {{ "BX35" , "13" } , {“CR20”, "10" } , {“FE15”, “12”}, {
"KW0”, “24”}, { "MM67" , "4" }}
Dim searchFor As String
Dim row As Integer
‘ assign the product ID to a variable
searchFor = idTextBox.Text
Do Until row = 5 OrElse searchFor = products(row, 0)
row = row + 1
Loop
' determine whether the product ID was found in the ids array
If row < 5 Then
priceLabel .Text = "$" & products(row, 1)
Else
MessageBox . Show( "Invalid product ID." , "Kaba LTD'' ,
MessageBoxButtons.OK, MessageBoxicon.Information)
53
End If
CICS 313: Visual Basic Programming - GTUC 2021
idTextBox.Focus() Delivery
Other Events
Private Sub idTextBox Enter( ByVal sender As Object ,ByVal e As
System.EventArgs.) Handles

idTextBox . SelectAll()

End Sub

Private Sub idTextBox TextChanged( ByVal sender As Object


,ByVal e As System.EventArgs.) Handles

priceLabel .Text = String .Empty

End Sub
54
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Any Questions?

55 CICS 313: Visual Basic Programming - GTUC 2021 Delivery

You might also like