Home » ASP.NET Basics » 07 - Writing code and handling events
7

Arrays

Defining function and uses of arrays

So far we have worked with variables. Variables are used for storing a single value. Consider a situation where we need to store multiple values such as salaries of 10 employees. We can create 10 different variables but using so many variables can be problematic. And what if we need to store salaries of 100 or 500 employees?

Arrays provide a solution for this problem. Using an array, we can store multiple values under a single name.

Arrays need to be declared before they can be used. The syntax is -

 data-type[ ] Array-name=new data-type[size];

For example,

 int[ ] salary=new int[10];

The above declaration creates an array. The name of the array is `salary'. The size of the array is 10 i.e. we can store 10 values in the array. The data type of the array is int. It means that all the 10 values in the array should be of the integer type.

salary

Values-

5000

6000

5800

6500

7000

8200

6400

5520

7700

6900

Index-

0

1

2

3

4

5

6

7

8

9

The figure above helps to imagine an array. Our example array `salary' has 10 values stored in it. Each value represents a salary. Each value has an index number associated with it. The index number starts with 0 and the last index number is 9, making it a total of 10 numbers.

The individual array elements (values) are accessed using their index numbers. For example, salary[0] represents the first value - 5000. Similarly, salary[7] represents the value 5520. In general terms, we can say that the individual element of an array can be represented as array-name[index-number].

We use a loop statement to go through all the elements of an array. Let us consider our `salary' array that contains the salary of 10 employees. Suppose each employee gets a bonus and we want to add this bonus to his or her salary. We can do it in this way:

 salary[0]=salary[0]+200; //the bonus, added to the salary of the first employee. salary[1]=salary[1]+200; salary[2]=salary[2]+200; . . . salary[9]=salary[9]+200;

This is a time consuming process. What if the array contains 100 or 500 elements?

A better approach is to use a loop -

 for (int i=0; i<10; i++) { salary[i]=salary[i]+200; }

Here, the integer variable `i' represents the index of the array. The loop will start with the value of `i' as 0 and continue till it gets to 9. Remember that the index numbers for our array are from 0 to 9. Inside the loop, 200 is added to each element of the array.

Another loop statement that can be used with arrays is the `foreach' loop. However, it is recommended that we do not make any changes to the array contents (values) inside the foreach loop. This loop is mainly used for reading the values of the array or processing the array in situations where the values if the array are not changed.

 foreach( int s in salary) { //code inside the loop }