Monday 24 December 2012

Arrays in QTP - Part 1


Hello Friends! In this post, we'll brush-up our understanding about vbscript arrays and to use arrays in QTP.


What is an Array?

- An array variable is used to store multiple values in a single variable.

- Array can contain a series of values of same data type.

- An array is a memory space referred by a common name.


Please note that VBScript explicitly supports only one data type - ‘Variant’. A variant can store a number as well as a string.

Arrays are of two types..


1. Static or Fixed Sized Array
2. Dynamic or Variable Sized Array


Both type of arrays can be of single dimensional or multi-dimensional. So to make the things simple, we can write this like...


1. Static or Fixed Sized Array
 
    1.1. Single dimensional Static Array   'Exp - Dim myArray(4)
    1.2. Multi-dimensional Static Array   'Exp - Dim myArray(3,4)


2. Dynamic or Variable Sized Array

    2.1. Single dimensional Dynamic Array
    2.2. Multi-dimensional Dynamic Array


Sounds batter? Okey.. great!!


Dim myArray(4)    'declaring array in vbscript


In the above example, an array containing 5 elements is declared:


But why 5? The number shown in the parentheses is 4!!

Ya! But array index actually starts from zero, so this array contains 5 elements. This is a fixed-size array.


You assign data to each of the elements of the array like this:

myArray(0)= 21
myArray(1)= 42
myArray(2)= 51
myArray(3)= 33
myArray(4)= 15


It was one way of declaring and assigning values to an array.
Here is the another way...

Dim myArray
myArray = Array(21,42,51,33,15)   'integer values
myArray = Array("val1","val2","val3","val4","val5")   'string values

It was the VBScript Array Method of Creating Arrays.

Array we have discussed above is Static Array - Single dimensions. A Static Array -

- has a pre-defined number of elements.
- size of a static array cannot be altered at run time.

Multiple dimensions are declared by separating the numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows and 7 columns:

Dim myArray(4,6)

In the above example, an array containing 5 rows and 7 columns has been declared.

Calculating the Size of Arrays:

ubound method is used to count the length of array. It returns the highest index number of the array.
But remember, the actual size of the array is highest index number plus one!! (since the array starts at index number 0).

Dim myArray(4),len1
len1 = ubound(myArray) '4
msgbox len1+1   '5


ubound method can be used to count the size of a multidimensional array also, but this time it's slightly different..

The dimension number needs to be included in ubound.

Dim myArray(4,6)
msgbox ubound(myArray, 1) 'It''' give highest index of the first dimension - 4
msgbox ubound(myArray, 2) 'It''' give highest index of the second dimension - 6

Tired! me too...!!

Please post your comments and tell me how you find this site!!

No comments:

Post a Comment