Wednesday, 11 January 2012

Arrays


Till now we have been using variable to store values. We might come across a situation
when we might need to store multiple values of similar type. Such as names of 100
students in a school. One way to do it is to declare 100 variables and store all the names.
A much more simple and efficient way of storing these variable is using Arrays. An
Array is a memory location that is used to store multiple values.
All the values in an array are of the same type, such as Integer or String and are
referenced by their index or subscript number, which is the order in which these values
are stored in the array. These values are called the elements of the array.
The number of elements that an array contains is called the length of the array.
In VB.Net all arrays are inherited from the System.Array Class.
Arrays can be single or multidimensional. You can determine the dimensions of an array
by the number of subscripts that are used to identify the position of any array element.
A single dimensional array is identified by only a single subscript and an element in a
two-dimensional array is identified by two subscripts.
The dimension has to be declared before using them in a program. The array declaration
comprises the name of the array and the number of elements the array can contain.
The Syntax of single dimension array is as follows.
Dim ArrayName (number of elements) as Element Data type.
e.g.
Dim studentname(10) as string
Or
Dim studentname() as string = new string(10)
You can assign the values at runtime or even at the design time.
Design time declaration:
Studentname(0)=”Rohan”
Studentname(1)=”Mohan”
…..
Studentname(10)=”Nitin”
All arrays starts with the index of 0 i.e. All arrays are Zero Based and there is no
provision of an option Base Statement where in you can specify the Lower Bound . This
implies that above array can store 11 elements. Here 0, is the starting index or the lower
bound of the array. The lower bound is fixed for all the arrays.
Example 1.
We will create a VB.Net application that will accept the names of students in an single
dimension array and display it back.
Add a textbox and set the name property to txtnames. Set the multilane property of the
text box to true.
Put a button and write the following in the onclick event.
txtnames.Text = ""
Dim value, count As Integer
'Accept how many students names to enter
value = CInt(InputBox("Enter the number of students name to enter:"))
Dim arrnames(value) As String
Dim cnt As Integer
For cnt = 0 To value
arrnames(cnt) = InputBox("Enter the name of student " & cnt + 1 & ":",
"Student Name")
Next
'Display the entered value to the text box
For cnt = 0 To value
If txtnames.Text = "" Then
txtnames.Text = arrnames(cnt) & vbCrLf ' for carriage returns
Else
txtnames.Text = txtnames.Text & arrnames(cnt) & vbCrLf
End If
Next
Above example will accept number of names to be entered and will add the names in a
loop and then redisplay it in a text box.
The Syntax for multi-dimension arrays is as follows:
Previously we saw how we can store multiple names of students. But, if we want to store
related data of students like first name, middle name, last name. In such situations you
can use multi dimension arrays, such as two-or-three dimension arrays.
Dim ArrayName (number of 1st element, number of 2nd element,….) as element data
type.
Or
Simpler form would be
Dim ArrayName( number of rows, number of columns) as element data type of two
dimension.
e.g.
Dim studentdetails(10,2) as string
Index positions of array elements.
0,0 0,1
1,0 1,1
2,0 2,1
3,0 3,1

10,0 10,1
studentdetails(0,0) = “Manoj”
studentdetails(0,1) = “Malik”
To display “Malik” we need to use the index position of the array and say ,
Studentdetails(0,1).
Example 2.
We will create a VB.Net application, which will accept Student Name, Address and city
name and display it in the text box in a formatted way.
As in the earlier example we will create a text box , change its name and its multi line
property to true.
Change the text box to txtsummary.
Add a button and write the below code in that.
Dim arrsummary(3, 3) As String
Dim i, j As Integer
'As we wanted just 3 columns we have set it to 2, else if u want to be
two only then while declaring the array make it (2,2) as the lower
index is 0.
For i = 0 To 2
For j = 0 To 2
arrsummary(i, j) = InputBox("Enter the value for " & i & " row _
and " & j & " column ", "Summary")
Next
Next
'Display the values in the summary array.
For i = 0 To 2
For j = 0 To 2
If txtsummary.Text = "" Then
txtsummary.Text = arrsummary(i, j)
Else
txtsummary.Text = txtsummary.Text & "-" & arrsummary(i, j)
End If
Next
txtsummary.Text = txtsummary.Text & vbCrLf
Next
Mohan #2/b,4th lane Kanpur
Mike 8th block csd NY
Lim Chou Lane Hong Kong
Dynamic Arrays.
Till now what we read were about fixed arrays. Let us see how we can manipulate the
size of an array at run time.
Many times we feel that the size of array in not enough or too much then required. As we
know that array will allocate memory location when its declared, so to release or add
more we need to change the dimension of the array which has been pre-declared.
We can create a dynamic array by not specifying the size of the array at the time of array
declaration.
Syntax:
Dim student_names() as string
In the above syntax you will see that number of elements are not mentioned. Now to redeclare
the elements we make use of ReDim for an array to change its dimension.
e.g.
Dim student_names() as string
ReDim student_names(10)
ReDim can also change the size of multi-dimensional arrays.
You can change the number of dimensions in an array, but you cannot make a multidimensional
array to a single dimension or lesser than the original dimension.
e.g.
Dim student_details(10,15) as string 'Declaring the array
ReDim student_details(10,25) 'Resizing the array
This statement does not change the data type of the array element or initialize the new
values for the array elements.
This statement can be used at the procedure level only not at the class level or module
level.
ReDim statements reinitializes the value of arrays with the respective data type declared
by the array.
If u have initialized the array to a some values it will be lost during the time of resizing
and the default values will be restored in those elements.
E.g.
'Declaring the array and initializing the value for the array
dim students_names() as string = {“Rahul”}
'This will display the value Rahul
msgbox(students_names(0))
Now resizing the array.
ReDim students_names(10)
'This will give a fixed size to 10 elements
msgbox(students_names(0))
This will display a blank value, as during the resizing the values of the array are
reinitialized to default value of string which is blank.
Now to avoid such problems we will make use of a keyword called Preserve while
resizing the array to new value.
Using the above example , we will make changes in the declaration.
ReDim students_names(10) 'The old declaration
ReDim Preserve students_names(10)
Students_names(1) = “Alex”
Students_names(2) = “Michael”
Msgbox(students_names(0))
This will display the value as ‘Rahul’ which we had initialized before resizing it. So
Preserve will restore all the initialized value of elements declared in an array.
If the array is an two or more dimensional array , you can only change the size of the last
dimension by using preserve keyword.
Dim student_details(10,20) as string
ReDim preserve student_details(15,25)
This will raise error because we are trying to change the first dimension also. So u can
only change the last dimension in case of multi-dimensional array.
Few Important methods in arrays.
Ubound() and Lbound().
Ubound is to get the upper limit of an array.
Lbound is to get the lower limit of an array by default lower limit is 0.
e.g.
Dim weeks() As String = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"}
Dim upper As Integer
Dim lower As Integer
upper = UBound(weeks)
lower = LBound(weeks)
MsgBox(upper.ToString & " - " & lower.ToString)
You will get 6 – 0 as the answer.
If you count the number of elements initialized elements its seven, but all arrays starts
with lower bound as 0. So from 0 – 6 is equal to 7 elements.
This works for single dimension , but for multi-dimensions,
We make use of the following:
Getupperbound(), getlowerbound() these functions are methods of the array class.
You can use it with single dimension also but best for multi-dimensional arrays.
Syntax : arrayname.getupperbound/getlowerbound(dimension)
Dimension refers to the which upper/lower bound should be found, 0 for first, 1 for
second and so on.
example.
Dim student_details(10,20,15)
Dim upperlimit as integer
upperlimit = student_details.getupperbound(0)
' This will return 10 for the 1st row element
upperlimit = student_details.getupperbound(1)
' This will return 20 for the 2nd row of element
For all getlowerbound(dimension) it will return 0 as the base lower bound is zero in .NET