Skip to main content

Multi-dimensional and Dynamic Array

One-dimensional arrays, such as those presented so far, are good for storing long sequences of one dimensional data (such as names or temperatures). But how you would store a list of cities and their average temperatures in an array? Or names and scores, years and profits, or data with more than two dimensions, such as products, prices, and units in stock? In some situations you will want to store sequences of multidimensional data. You can store the same data more conveniently in an array of as many dimensions as needed.
A two-dimensional array has two indices. The first identifies the row (the order of the city in the array), and the second identifies the column (city or temperature). To access the name and temperature of the third city in the two-dimensional array, use the following indices:
                        Temperatures (2, 0)                ‘the third city’s name’
                        Temperatures (2, 1)                ‘the third city’s temperature

The benefit of using multidimensional arrays is that they’re conceptually easier to manage. Suppose you’re writing a game and want to track the positions of certain pieces on a board. Each square on the board is identified by two numbers, its horizontal and vertical coordinates. The obvious structure for tracking the board’s squares is a two-dimensional array, in which the first index corresponds to the row number and the second corresponds to the column number. The array could be declared as follows:
            Dim Board(9, 9) As Integer
It is possible to initialize a multidimensional array with a single statement, just as you do with a one-dimensional array. You must insert enough commas in the parentheses following the array name to indicate the array’s rank. The following statements initialize a two-dimensional array and then print a couple of its elements:
            Dim a(,) As Integer = {{1, 2, 3}, {11,  12, 13}, {21,  22, 23}}
            Console.Writeline(a(0, 1))                  ‘will print 20
            Console.Writeline(a(2, 2))                  ‘will print 32

If the array has more than one dimension, you can find out the number of dimensions with the Array.Rank property. Let’s say you have declared an array for storing names as salaries with the following statements:
            Dim salaries(1, 99) As Object
To find out the dimensions, use the statement:
salaries.Rank
when using the Length property to find out the number of elements in a multi-dimensional array, you will get back the total number of elements in the array – 2 x 100, for our example. To find out the number of elements in a specific dimensions use the GetLength method, passing as argument a specific dimension. The following expression will return the number of elements in the first dimension of the array:
Console.Writeline (salaries.GetLength(0))
Since the index of the first element is zero, the index of the last element is the length of the array minus 1. Let’s say you have declared an array with the following statement to store player statistics for 15 players, and there are 5 values per player:
The following statement will return the values shown beneath them, in bold:
Console.WriteLine(Statistics.Rank)
2                      ‘dimensions in array
Console.WriteLine(Statistics.Length)
75                    ‘total elements dimension
Console.WriteLine(Statistics.GetLength(0))
15                    ‘elements in first dimension
Console.WriteLine(Statistics.Length(1))
5                      ‘elements in second dimension
Console.WriteLine(Statistics.GetUpperBound(0))
14                    ‘last index in the first dimension
Console.WriteLine(Statistics.GetUpperBound(1))
4                      ‘last index in the second dimension


Dynamic Arrays
Sometimes you may not know how large to make an array. Instead of making it large enough to hold the maximum number of data, you can declare a dynamic array. The size of a dynamic array can vary during the course of the program. Or you might need an array until the user has entered a bunch of data and the application has processed it and displayed the results. Why keep all the data in memory when it is no longer needed? With a dynamic array, you can discard the data and return the resources it occupied to the system.
To create a dynamic array, declare it as usual with the Dim statement (or Public or Private) but don’t specify its dimensions:
Dim DynArray() As Integer
The ReDim statement can appear only in a procedure. Unlike the Dim statement, ReDim is executable – it forces the application to carry out an action at runtime. Dim statements aren’t executable, and they can appear outside procedures.

The Preserve Keyword
Each time you execute the ReDim statement, all the values currently stored in the array are lost. Visual Basic resets the values of the elements as if they were just declared. (It resets numeric elements to zero and String elements to empty strings.)
In most situations, when you resize an array, you no longer care about the data in it. You can, however, change the size of the array without losing its data. The ReDim statement recognizes the Preserve Keyword, which forces it to resize the array without discarding the existing data. For example, you can enlarge an array by one element without losing the values of the existing elements by using the UBound() function as follows:
            ReDim Preserve DynamicArray(UBound(DynArray) + 1)
If the array DynamicArray held 12 elements, this statement would add one element to the array, the element DynamicArray(12). The values of the elements with indices 0 through 11 wouldn’t change. The UBound() function returns the largest available index (the number of elements) in one-dimensional array. Similarly, the LBound() function returns the smallest index. If an array was declared with the statement
            Dim Grades(49) As Integer
then the function LBound(Grades) and UBound(Grades) would return the values 0 and 49.

Resources Used:

1. Mastering in VB.NET
2. Black Book

Compiled By: Chaudhary Amit V.

Comments

Popular posts from this blog

Characteristics of a Good Programming Language

Till now there are many high level languages which are very popular, and there are others, which could not become so popular in-spite of being very powerful. There might be many reasons for the success of a language, but one obvious reason is the characteristics of the language. Several characteristics believed to be important with respect to making a programming language good are briefly discussed below. Simplicity A good programming language must be simple and easy to learn and use. For example, BASIC is liked by many programmers only because of its simplicity. Thus, a good programming language should provide a programmer with a clear, simple and unified set of concepts which can be easily grasped. It is also easy to develop and implement a compiler or an interpreter for a programming language that is simple. However, the power needed for the language should not be sacrificed for simplicity. The overall simplicity of a programming language strongly affects the readability of the pr...

Angular 4 and Firebase Authentication: Setup

If you have come to this article, it means you are keen to learn new technology and that too Firebase. I love Firebase because it provides all basic but important features of any web application. Take for example, authentication, which is cumbersome and risky if not implemented with utmost care. And when we have the integration of Angular and Firebase, it becomes a lot easier for a developer to build such crucial modules in less time with minimal efforts. In this article we will create a simple Angular application using Firebase. I am going ahead with the understanding that you know the benefits of Firebase and have little knowledge about it. There are plenty of posts out on the web if you are behind. Step 1: Install Angular CLI (if not installed). npm install -g angular-cli Step 2: Create new Angular 4 project. By default now angular CLI will create Angular 4 project so you need not fret. ng new firebase-authentication Step 3: Check whether the ne...

Switch-case, simple calculator . . .

11.      Write a program to perform some mathematic functions with the help of “switch-case” statement. #include<stdio.h> #include<conio.h> void main() { int a,b,ans; char c; clrscr(); printf("\ Enter a and b:"); scanf("%d%d",&a,&b); printf("\n Enter operator:"); fflush(stdin); scanf("%c",&c); switch(c) { case'+':ans=a+b;       break; case'-':ans=a-b;       break; case'*':ans=a*b;       break; case'/':ans=a/b;       break; } printf("\n ans %d",ans); getch(); } 12.      Print the Fibonacci series #include<stdio.h> #include<conio.h> void main() { int a=1,b=1,s=3,c,ch; clrscr(); printf("how many steps="); scanf("%d",&ch); printf("%5d%5d",a,b); for(s=3;s<=ch;s++) {       c=a+b;       printf("%5d",c);       a=b;    ...