December 2016 ~ is a programming blog which focused on Web Programming and development

Thursday, 29 December 2016

Working with Arrays in C Sharp Programming

22:43:00 Posted by raviteja swayampu No comments

Programming in C Sharp

Programming in C Sharp is a Series of self taught article.Till now i shared my experience in the form of small applications and code samples.From now on wards i want to share Technologies(C Sharp,ASP.NET MVC,Angular Js,Jquery) knowledge step by step in series of tutorials to help the beginner people who want to start their career in web development using Microsoft Web Technologies .I will start this series with Arrays Concept in C Sharp Programming.


In this article i will focus on Arrays.Arrays is the most wanted concept in C Sharp Programming.This article starts with the basic definition of arrays and ends with Arrays classes and how to search,sort with arrays items.For better readability i am diving this tutorial into two parts.

Array is a data structure that stores the multiple variables of same type.Unlike other data structures arrays are fixed in size.It's index start with 0 and end with (n-1). Where n=number of elements in array.For Example if an array contains 5 elements it's index start with 0 th element and ends with 4 th index element.

Why we need Arrays

Consider a situation where we need to store five integer numbers. If we use programming's simple variable and data type concepts, then we need five variables of int data type.with variables the program will look like below.
   main() {
   int  num1;
   int  num2;
   int  num3;
   int  num4;
   int  num5;
   num1 = 10;      
   num2 = 20;   
   num3 = 30;   
   num4 = 40; 
   num5 = 50;     

   printf( " num1: %d\n", num1);
   printf( " num2: %d\n", num2);
   printf( " num3: %d\n", num3);
   printf( " num4: %d\n", num4);
   printf( " num5: %d\n", num5);
It was simple, because we had to store just five integer numbers. Now let's assume we have to store 5000 integer numbers. Are we going to use 5000 variables?

To handle such situations, almost all the programming languages provide a concept called array. An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Memory allocation in arrays:

Defining Arrays: 
In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator. The following code snippet defines arrays of double, char, bool, and string data type.
double[] doubleArray = new double[5];
char[] charArray = new char[5];
bool[] boolArray = new bool[2];
string[] stringArray = new string[10];

Initializing Array:
1.In above code snippet we have declared arrays with different data types.Now we have to initialize that arrays with some actual data.
int[] numArray=int[5]{1,2,3,4,5};
2.In above line of code i initialized the 'numArray' with 5 integer elements.
3.we can also add this one item at a time in array like below.
int[] numArray= new int[5];
numArray[0] = 1;
numArray[1] = 2;
numArray[2] = 3;
numArray[3] = 4;
numArray[4] = 5;
4.OR we can dynamically initialize an array(with specifying size) using actual data.
string[] monthArray=string[]{'january','feb','march'};

Accessing Arrays:
5.We can access those array items with help of index.for example i will print above 'monthArray' in program like below.
Note: This approach is suited when you know the exact element to access.
Console.WriteLine("First Month: "+monthArray[1]);
Console.WriteLine("Second Month: "+monthArray[2]);
Console.WriteLine("Third Month: "+monthArray[3]);
6.Ok,accessing array using index is fine but if there are hundreds of elements present in array how you are going to access those elements.In that case we will go to Foreach loop.Foreach loop is best suited for arrays.The following code snippet shows how to print all elements in 'monthArray' array.
//Read all elements in array
foreach(var item in monthArray){

Note: This approach is best suited when you do not know the exact index of element in array.
vTypes of Arrays
Arrays are divided into four types.
1.Single Dimensional or linear arrays
2.Multi dimensional or rectangular arrays.
3.Jagged arrays.

Single Dimensional Arrays:
Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored contiguously starting from 0 to the size of the array -1.
The following code declares an integer array that can store 3 items. As you can see from the code, first I declare the array using [] bracket and after that I instantiate the array by calling the new operator.
int[] intArray;
intArray = new int[3];
Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialized, its items are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is declared.
The following code declares and initializes an array of three items of integer type.
int[] staticIntArray = new int[3] {1, 3, 5};

//declares and initializes an array of 5 string items.
string[] strArray = new string[5] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
//You can even directly assign these values without using the new operator.
string[] strArray = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
//You can initialize a dynamic length array as follows:
string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };

Multi Dimensional Arrays:
A multi-dimensional arrays are also known as a rectangular array contains more than one dimension. The form of a multi-dimensional array is a matrix.It can be fixed-sized or dynamic sized.
A multi dimension array is declared as following:
string[,] mutliDimStringArray;
See following code snippet is an example of fixed-sized multi-dimensional arrays that defines two multi dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array can store 4 items. Both of these arrays are initialized during the declaration.
int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[2, 2] { { "Ravi", "Anu" }, { "Gopal", "Thomas" } };
We can declare in run time also.The following code snippet creates matrix array with unlimited size.
int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[,] { { "Ravi", "Anu" }, { "Gopal", "Thomas" } };
we can also omit the new operator also
int[,] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
We can also initialize the array items one item at a time. The following code snippet is an example of initializing array items one at a time.
int[,] numbers = new int[3, 2];
numbers[0, 0] = 1;
numbers[1, 0] = 2;
numbers[2, 0] = 3;
numbers[0, 1] = 4;
numbers[1, 1] = 5;
numbers[2, 1] = 6;
Accessing Multi Dimensional Arrays:
A multi-dimensional array items are represented in a matrix format and to access it's items, we need to specify the matrix dimension. For example, item(1,2) represents an array item in the matrix at second row and third column.
Check the below lines of code for detail.

Console.WriteLine(numbers[0, 1]);
Console.WriteLine(numbers[2, 0]);
Console.WriteLine(numbers[2, 2]);
Jagged Arrays:
Jagged arrays are arrays of arrays or we can also called as nested arrays.Because here the elements of the Jagged arrays are arrays.
Initializing Jagged Arrays:
Before a jagged array can be used, its items must be initialized. The following code snippet i initialized a jagged array.The first item with an array of integers that has two integers and second item with an array of integers that has 4 integers.
int[][] JaggedArray[0] = new int[2];
int[][] JaggedArray[1] = new int[4];
We can also initialize a jagged array's items by providing the values of the array's items(during the declaration).
int[][] JaggedArray[0] = new int[2]{2, 12};
int[][] JaggedArray[1] = new int[4]{4, 14, 24, 34};
Accessing Jagged array Elements
we can access jagged arrays individually using below code.
To access more elements at we can loop the array using foreach loop.For this the arrays properties help a lot(Ex:Length property).
Following code loops the Jagged array elements and displays output.
for (int i = 0; i < intJaggedArray3.Length; i++)
    System.Console.Write("Element({0}): ", i);
    for (int j = 0; j < intJaggedArray3[i].Length; j++)
        System.Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" : " ");


This is about different types of arrays in C sharp programming.I hope this tutorial may helpful for understanding Arrays concept in C Sharp for beginners.In next tutorial i will explain about Array Classes and array class properties and methods.
If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].