Course C# Programming Basics for Beginners
.Net C# CSharp

Arrays in C#

( 13 users )

Arrays in C#

In C#, an Array is a collection of elements of the same data type. The data types can either be a value type or reference type. Arrays are very useful in any programming language because accessing an item from a collection becomes very easy. An array uses index or position of the item to access it. For e.g. in an array of 10 elements, if we want to access the 6th element of the array, we can specify the index or position with array name. Please note that the array index in C# starts from 0. This also makes Array a perfect candidate for iteration within a loop where we can dynamically access different elements based on position.

Declaring an Array

The general syntax of defining an array is:

data-type[] array-name;

We suffix the data type with square brackets [] to indicate that variable "array-name" is an array of type "data-type". For e.g.


int[] ages;
			

Here, the variable ages is an array of type int.

Initializing an Array

The elements of an array are allocated contiguous memory locations in the memory. For e.g. to allocate memory to an array of 10 elements of int data type, the CLR blocks (size-of-integer)*10 bytes of memory and assign it to the array. We use a new keyword and mention the number of elements in the array. The general format initializing an array is as follows.

data-type[] array-name = new data-type[number-of-items];

As you can see we have used new keyword and suffixed data-type with a value (number of items) inside the square brackets. For e.g.


int[] ages = new int[5];
			

Here, the array ages can contain 5 elements of integer types. We, however, do not have any items assigned to the array. This is how we can do that.


ages[0] = 21;
ages[1] = 25;
ages[2] = 19;
ages[3] = 32;
ages[4] = 27;
			

Just like initializing a variable we can initialize each element of an array. The only difference being we have a suffixed index number under square brackets to the array variable so as to assign the value at a particular position or index in the array.

In C#, there are other short-cut ways in which we can initialize an array as well as its element at the same time. This is how we can do that.


int[] ages = new int[5] {21, 25, 19, 32, 27};
			

In the above example, we formed a "set" kind of structure with 5 elements inside and suffixed it at the end of the array initialization. Even though the above initialization is fine, however, we need not specify the length. The compiler can infer from the number of elements present in the set. Hence, we can omit the length specification. See the example below.


int[] ages = new int[] {21, 25, 19, 32, 27};
			

You might be thinking that if the compiler can infer the information from the set of elements, then why even we are writing "new int[]", the compiler can also infer the type and initialize according to the set. Well, you are thinking right. We can also omit the "new int[]" part as well when initializing in this way.


int[] ages = {21, 25, 19, 32, 27};
			

The above mentioned initialization is absolutely fine as well.

Accessing elements within an array

If we want to access and print the 3rd element of the above array, we can do it as:


Console.WriteLine("3rd element of array ages is " + ages[2]);
			

There is a property (Properties we will cover later in this course) associated with an Array called Length. It gives us the total number of elements in an Array.


int length_of_array = ages.Length;
Console.WriteLine(length_of_array);
			

It will print 5 to the console.

If we want to access and print all values of an array, using loops is the best way of doing that.


for(var i=0; i < ages.Length; i++)
{
	Console.WriteLine("Age of person - " + i + " = " + ages[i]);
}
			

Types of Arrays

We are going to categories the arrays in terms of its dimensions.

Single dimensional array

If you are from a mathematics background, you probably understand the concepts of dimensions. In the above examples, "ages" array is a single dimensional array. It corresponds to a vector in mathematics. A vector is a collection of items in one-dimensional space. A single dimensional array is simply a collection of similar items. For e.g. To store students' marks (in one subject only) only we can create a single dimensional array as follows.


int[] students = {75, 62, 94, 83, 87};
			

From above statement we can say that the marks of 3rd student in a specific subject is 94. Let's see another example.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("-- Single dimensional array --");
		Console.WriteLine("");
			
		int[] ages = {21, 25, 19, 32, 27};
		
		for(int i=0; i < ages.Length; i++)
		{
			Console.WriteLine("Age of person - " + i + " = " + ages[i]);
		}
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}
			

Multi dimensional array

A multi-dimensional array is an array where the elements of an array are spanned across 2 or more dimensional. Let's understand this with a simple two-dimensional array. A two-dimensional array is similar to a matrix (mathematics) or a table with rows and columns.

Continuing with above example, if we want to add marks not just one subject but say in 5 subjects of each student in the same array, we can do that in a two dimensional array. The first dimension being a students and the second dimension being marks of each of the students. This is how we can do that.


int[ , ] students = {
		{ 75, 81, 86, 77, 67 },
		{ 62, 71, 76, 68, 78 },
		{ 94, 91, 95, 88, 87 },
		{ 83, 88, 75, 71, 72 },
		{ 87, 77, 79, 88, 81 }
	};
			

This creates a two-dimensional array student with size [5, 5] (5 students with marks in 5 subjects).

From the above statement we can say that the marks of 3rd student in 5 different subjects are { 94, 91, 95, 88, 87 }. The marks of this 3rd student in 4th subject is 88 and we can access and print this as follows.


Console.WriteLine("Marks of 3rd student in 4th subject = " + students[2, 3]);
			

In the similar way, an nth dimensional array can be created and initialized. However, it becomes difficult to visualize as we keep on adding more dimensions to an array. Single and two-dimensional arrays have most use cases fulfilled.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("-- Multi dimensional array --");
		Console.WriteLine("");
			
		int[ , ] students = {
			{ 75, 81, 86, 77, 67 },
			{ 62, 71, 76, 68, 78 },
			{ 94, 91, 95, 88, 87 },
			{ 83, 88, 75, 71, 72 },
			{ 87, 77, 79, 88, 81 }
		};

		for(int i=0; i < 5; i++)
		{
			Console.WriteLine("Marks of Student - " + i);
			Console.WriteLine("-----------------------------------");
			for(int j=0; j < 5; j++)
			{
				Console.WriteLine("\t Subject - " + j + " = " + students[i, j]);
			}
			Console.WriteLine("");
		}
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}
			

Jagged Array

A jagged array is also called an "array of array". It is not a multi-dimensional array. The difference is that in Jagged array, each element of a a jagged array can have an array with variable number of elements. A jagged array is declared as follows.

data-type[][] jagged-array-name = new data-type[number-of-arrays][];

The data type is followed by two square brackets. The first one indicates number of arrays it can have. The other indicates the number of elements in a specific array. Let's see this difference with the help of an example.


int[][] lists = new int[3][];
	
lists[0] = { 1, 2, 3, 4 };
lists[1] = { 4, 5 };
lists[2] = { 6, 7, 8, 9, 10 };
			

In the above example, first we declared a jagged array having number of arrays equals to 3. Then, we initialized each of the three arrays with some elements. This is the reason it is called Array of Arrays. To access items in a Jagged array, we simply mention the array index and item index.


Console.WriteLine(list[1][1]);
			

The above line will print the second item from the second array of lists. Here is the complete example.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("-- Jagged array --");
		Console.WriteLine("");

		int[][] lists = new int[3][];
	
		lists[0] = new int[ 3 ] { 1, 2, 3 };
		lists[1] = new int[ 2 ] { 4, 5 };
		lists[2] = new int[ 5 ] { 6, 7, 8, 9, 10 };

		for(int i=0; i < lists.Length; i++)
		{
			Console.WriteLine("Items in list - " + i);
			Console.WriteLine("-----------------------------------");
			for(int j=0; j < lists[i].Length; j++)
			{
				Console.Write(lists[ i ][ j ] + "\t");
			}
			Console.WriteLine("");
			Console.WriteLine("");
		}
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}
			

To Do

* Note : These actions will be locked once done and hence can not be reverted.

1. Track your progress [Earn 200 points]

2. Provide your ratings to this chapter [Earn 100 points]

0
Control flow statements
String manipulations
Note : At the end of this chapter, there is a ToDo section where you have to mark this chapter as completed to record your progress.