Arrays - C# Programming for Beginners (2015)

C# Programming for Beginners (2015)

Chapter 5: Arrays

Suppose you have to store the salaries of three employees. You can declare three integer type variables which can store those salaries. What if you have to store the salaries of one hundred employees? Will you declare one hundred integer type variables and then individually store the salary of each employee in one variable? This is one solution. However, accessing variables this way is very cumbersome. Also, this approach results in verbose code. A better approach is to use C# arrays. An array contains a collection of items of a particular type. Arrays store data in contiguous memory locations which improves its efficiency. Each item in an array is called.

Contents:

· Array Syntax

· One-dimensional Array

· Two-dimensional Array

1- Array Syntax

An array has the following syntax:

type [] array-name = new type [size];

An array starts with the type of element it is going to store, followed by a square bracket and finally the name of the array. At this point in time, an array is only declared and no memory locations are reserved for it. To initialize an array, you use the “new” keyword followed by the type of the array. This is followed by square brackets, and, inside those square brackets, you specify the size of the array. The size specifies the number of elements an array can store. The following piece of code specifies how to initialize an integer type array named salaries with a size of 10.

int [] salaries = new int [10];

2- One-Dimensional Array

An array which stores elements in one direction, i.e. in the form of a column or row, is called a one-dimensional array. The “salaries” array which we declared in the last section was a one-dimensional array. A one-dimensional array is initialized using one square bracket after the array type. To see a one-dimensional array in action, have a look at the first example of this chapter.

Example1:

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

int[] salaries = new int[10] { 78, 15, 27, 87, 56, 74, 12, 36, 98, 41 };

int a = salaries[0];

int b = salaries[5];

Console.WriteLine(a + b);

salaries[0] = 25;

salaries[5] = 25;

a = salaries[0];

b = salaries[5];

Console.WriteLine(a + b);

Console.Read();

}

}

}

In Example1, we initialized the array “salaries” and stored 10 elements in this array at initialization time. This is one way to store elements in the array. You initialize the array and, on the same line, you enter the elements inside the curly brackets that follow after the square brackets containing the size. Inside the curly bracket, you separate each element with a comma. An array has a zero based storage index. This means that the first element of the array is stored at 0th index while the last element is stored at n-1st index, where n is the size of the array. To access the element at any index, you use the name of the array followed by square brackets. Inside the square brackets, you mention the index. For instance, in Example1, the element at the 0th index of the salaries array is stored in integer variable “a”, while the element at the 5th index is stored in variable “b”. On the console, the sum of these two variables is printed. Then the array indexes zero and five are updated with value 25. On the console window, their sum is again printed, which now contains the updated value. The output of the code in Example1 is shown below.

Output1:

152

50


In Chapter 4, we studied the “foreach” loop, which can be used to iterate over any set or list of items. In addition to the “foreach” loop, the “for” loop can also be used to iterate over an array. In Example2, we shall see how an array can be iterated via “for” and “foreach” loops.

Example2:

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

int[] salaries = new int[10] { 78, 15, 27, 87, 56, 74, 12, 36, 98, 41 };

for (inti = 0; i< 10; i++ )

{

Console.Write(salaries[i] + " ");

}

Console.WriteLine();

foreach (int n in salaries)

{

Console.Write(n+" ");

}

Console.Read();

}

}

}

In Example2, the “salaries” array has again been initialized with some random variables. We first iterated the array with a “for” loop, then we iterated over the “salaries” array using a “foreach” loop. The output of the code in Example2 is as follows.

Output2:

78 15 27 87 56 74 12 36 98 41

78 15 27 87 56 74 12 36 98 41

3- Two-dimensional Array

A one-dimensional array stores data in the form of a single column or row. A two-dimensional array, often referred as an array of arrays, stores data in the form of multiple rows and columns. Data is stored in the memory in the form of a matrix. To initialize a two-dimensional array, you simply have to put a comma inside the square bracket that follows after the type of the array. On the left side, after the new keyword and inside the square brackets, you have to mention the number of rows and columns that the array will contain. Rows and columns should be separated by commas. Look at Example3 to see two-dimensional arrays in action.

Example3:

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

int[,] salaries = new int [2,3];

salaries[0,0] = 10; // First row first column

salaries[0,1] = 20; // First row second column

salaries[0, 2] = 30; // First row third column

salaries[1, 0] = 40; // 2nd row first column

salaries[1, 1] = 50; // 2nd row second column

salaries[1, 2] = 60; // 2nd row third column

for (inti = 0; i< 2; i++)

{

for (int j = 0; j < 3; j++)

{

Console.Write(salaries[i, j]+" ");

}

Console.WriteLine();

}

Console.Read();

}

}

}

In Example1, we initialized a two-dimensional array, “salaries”, with two rows and three columns. We then accessed each index and stored some random integer values. To access a particular index of a two-dimensional array, you write the name of the array followed by the square bracket. Inside the square brackets, you first enter the row number, then comma, and then the column number. To iterate over a two-dimensional array requires nested “for” loops where the outer loop iterates over each row and the inner loop iterates over each column. This is demonstrated in Example3. The output of the code in Example3 is as follows.

Output3:

10 20 30

40 50 60

Exercise 5

Task:

Using nested “for” loops, store the table of 2,3,4, and 5 in a two-dimensional array and then display the elements of the array on screen.

Solution

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

int[,] tables = new int [4,10];

for (inti = 2; i< 6; i++)

{

for (int j = 0; j <10; j++)

{

tables[i-2,j] = i*(j+1);

}

}

for (inti = 0; i< 4; i++)

{

for (int j = 0; j < 10; j++)

{

Console.Write(tables[i, j]+" ");

}

Console.WriteLine();

}

Console.Read();

}

}

}