Arrays fundamentals in C#.Net

Arrays

An array is a variable that can store more than one value of same data type. A normal variable can store only one value and when you want to store more than one value in a variable then declare that variable as an array. In C# array element index starts with zero and ends with size -1 same as in case of an array in C.

One Dimensional Arrays
An array that has only one row of elements is called as one dimensional array. To create a variable as a one dimensional array, syntax will be as follows.

Declaration Syntax              

 Datatype[ ] ArrayName = new Datatype[Size];
           
Ex                                            
int[ ] A=new int[5];
 int[ ] A;
A=new int[5];

Example : The following example, creates a one dimensional array of integers, dynamically allocates memory to it , read values in to it and prints those values.

namespace Language
{
    class ODArray
    {
        static void Main()
        {
            int[] A;
            byte Size;
            Console.Write("Enter Size of The Array : ");
            Size = byte.Parse(Console.ReadLine());
            A = new int[Size];
            Console.WriteLine("Enter {0} Elements", Size);
            for (int i = 0; i < Size; i++)
            {
                A[i] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("Elements In Array Are...");
            foreach (int n in A)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
        }
    }
}

Example : The following example creates a one dimensional array of integers , read values in to it and then find a given element in the array.

namespace Language
{
    class ODArraySearch
    {
        static void Main()
        {
            int[] A;
            byte Size,e,i;
            Console.Write("Enter Size Of The Array : ");
            Size = byte.Parse(Console.ReadLine());
            A = new int[Size];
            Console.WriteLine("Enter {0} Elements", Size);
            for (i = 0; i < Size; i++)
            {
                A[i] = int.Parse(Console.ReadLine());
            }
            Console.Clear();
            Console.Write("Enter The Element You Want To Search For : ");
            e = byte.Parse(Console.ReadLine());
            for (i = 0; i < Size; i++)
            {
                if (A[i] == e)
                {
                    Console.WriteLine("Element Found At Index {0}", i);
                    break;
                }                   
            }
            if (i == Size)
                Console.WriteLine("Element Was Not Found");
        }
    }
}

Example : The following example creates a one dimensional array of integers , reads values in to that array and prints those values in ascending order.

namespace Language
{
    class ODArraySort
    {
        static void Main()
        {
            int[] A;
            byte Size;
            Console.Write("Enter Size Of the Array : ");
            Size = byte.Parse(Console.ReadLine());
            A = new int[Size];
            Console.WriteLine("Enter {0} Elements", Size);
            for (int i = 0; i < Size; i++)
            {
                A[i] = int.Parse(Console.ReadLine());
            }
            Console.Clear();
            Console.WriteLine("Elements In Array Are...");
            foreach (int n in A)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
            for (int i = 0; i < Size; i++)
            {
                for (int j = i + 1; j < Size; j++)
                {
                    if (A[i] > A[j])
                    {
                        int T = A[i];
                        A[i] = A[j];
                        A[j] = T;
                    }
                }
            }
            Console.WriteLine("Elements In Ascending Order Are...");
            foreach (int n in A)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
        }
    }
}

Two Dimensional Arrays
A two dimensional array is an array with more than one row of elements and is similar to a matrix. To declare a variable as two dimensional array syntax will be as follows.

Declaration Syntax               
Datatype[ , ] ArrayName = new Datatype[Rows,Cols];
                       
Ex:                                     
     int[ , ] A = new int[3,3];
     int[ , ] A;
     A = new int[3,3];

When a variable is declared as an array then it will have the following methods that can be used to get the size of the array.

Member Name
Description
GetLength(Dimension)
Returns the total no. of elements in specified dimension of the array.
GetUpperbound(Dimension)
Returns the index of last element in specified dimension.
Length
Returns total no. of elements in the array.
Rank
Returns the no. of dimensions of the array.

For example if an a two dimensional is declared as int [ , ] A = new int[ 7, 5 ]; then
A.GetLength(0) will return 7 i.e. Total no. of rows
A,GetLength(1) will return 5 i.e. Total no. of columns
A.GetUpperbound(0) will return 6 i.e. index of the last row
A.GetUpperbound(1) will return 4 i.e. index of the last column
A.Length will return 35 i.e. total no. of elements in the array and
A.Rank will return 2 i.e. no. of dimensions of the array

For example if a one dimensional is declared as int [ ] A = new int[10]; then
A.GetLength(0) will return 10 i.e. total no. of elements in array
A.GetUpperbound(0) will return 9 i.e. index of last element in the array
A.Length will return 10 i.e. total no. of elements in array And
A.Rank will return 1 i.e. no. of dimensions of the array

Example : The following example creates a two dimensional array of integers , reads values in to it and prints those values.

namespace Language
{
    class TDArray
    {
        static void Main()
        {
            int[,] A;
            byte R, C;
            Console.WriteLine("Enter Order Of The Matrix");
            R = byte.Parse(Console.ReadLine());
            C = byte.Parse(Console.ReadLine());
            A = new int[R, C];
            Console.WriteLine("Enter {0} Elements", R * C);
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                {
                    A[i, j] = int.Parse(Console.ReadLine());
                }
            }
            Console.WriteLine("Elements In Array Are...");
            for (int i = 0; i < A.GetLength(0); i++)
            {
                for (int j = 0; j < A.GetLength(1); j++)
                {
                    Console.Write("{0}\t", A[i, j]);
                }
                Console.WriteLine();
            }
        }
    }
}

Example : The following example creates two two dimensional array of integers and calculates the sum of those two matrices.

namespace Language
{
    class MatrixSum
    {
        static void Main()
        {
            int[,] A, B, S;
            byte R, C;
            Console.WriteLine("Enter Order Of The Matrix");
            R = byte.Parse(Console.ReadLine());
            C = byte.Parse(Console.ReadLine());
            A = new int[R, C];
            B = new int[R, C];
            S = new int[R, C];
            Console.WriteLine("Enter {0} Elements For The First Array", R * C);
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                {
                    A[i, j] = int.Parse(Console.ReadLine());
                }
            }
            Console.WriteLine("Enter {0} Elements For The Second Array", R * C);
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                {
                    B[i, j] = int.Parse(Console.ReadLine());
                }
            }
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                {
                    S[i, j] = A[i, j] + B[i, j];      
                }
            }
            Console.WriteLine("Sum Matrix Is...");
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                {
                    Console.Write("{0}\t", S[i, j]);
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }
    }
}

Example : The following example creates two two dimensional array of integers and calculates the product of those two matrices.

namespace Language
{
    class MatrixSum
    {
        static void Main()
        {
            int[,] A, B, P;
            byte R, C;
            Console.WriteLine("Enter Order Of The Matrix");
            R = byte.Parse(Console.ReadLine());
            C = byte.Parse(Console.ReadLine());
            A = new int[R, C];
            B = new int[R, C];
            P = new int[R, C];
            Console.WriteLine("Enter {0} Elements For The First Array", R * C);
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                {
                    A[i, j] = int.Parse(Console.ReadLine());
                }
            }
            Console.WriteLine("Enter {0} Elements For The Second Array", R * C);
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                {
                    B[i, j] = int.Parse(Console.ReadLine());
                }
            }
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                {
                    P[i, j] = 0;
                    for (int k = 0; k < C; k++)
                    {
                        P[i, j] += A[i, k] * B[k, j];
                    }
                }
            }
            Console.WriteLine("Product Matrix Is...");
            for (int i = 0; i < R; i++)
            {
                for (int j = 0; j < C; j++)
                {
                    Console.Write("{0}\t", P[i, j]);
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }
    }
}

Jagged Arrays
A jagged array is an array of one dimensional array. It looks similar to a two dimensional array but is different from a two dimensional array in that in a two dimensional array every row must have same number of columns while in a jagged array each one dimensional array can be of different size.

Declaration Syntax  
Datatype[ ] [ ] ArrayName = new Datatype[ M ] [ N ];

Ex : int[ ] [ ] A = new int[3][5];

In the above declaration, variable A is declared as a jagged array with 3 one dimensional arrays where the size of each one dimensional array is 5.
           
Ex :                                      
   int[ ] [ ] A = new int[3][ ];
   A[0] = new int[2];
  A[1] = new int[3];
  A[2] = new int[4];

In the above declaration, variable A is declared as a jagged array with 3 one dimensional arrays where the size of first one dimensional array is 2, second one dimensional array is 3 and third one dimensional array is 4.

Example : The following example creates a jagged array of integers with three one dimensional arrays and first values are read in to only second one dimensional array in the jagged array and are printed and then values are read in to all three one dimensional arrays and are get printed.

namespace Language
{
    class JArrays
    {
        static void Main()
        {
            int[][] A = new int[3][];
            A[0] = new int[2];
            A[1] = new int[3];
            A[2] = new int[4];
            Console.WriteLine("Enter 3 Integers");
            for (int i = 0; i < 3; i++)
            {
                A[1][i] = int.Parse(Console.ReadLine());
            }
       Console.WriteLine("Elements In Second One Dimensional In JaggedArray Are...");
            foreach (int n in A[1])
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
            Console.WriteLine("Enter 9 Elements");
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < A[i].GetLength(0); j++)
                {
                    A[i][j] = int.Parse(Console.ReadLine());
                }
            }
            Console.WriteLine("Elements In Jagged Array Are...");
            for (int i = 0; i < 3; i++)
            {
                foreach (int n in A[i])
                {
                    Console.Write("{0}\t", n);
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }
    }
}

Array Class
.net framework provides a class with the name Array that provides various methods that simplify various operations on an array like sorting and searching. The methods available in Array class are as follows.

1. BinarySearch(Array,Element):
 Searches for given element in given array using binary search logic and returns the index of that element if it was found and other wise a negative value. The following example searches for an element in the array using binarysearch method of array class.

namespace Language
{
    class ArrayBinarySearch
    {
        static void Main()
        {
            int[] A ={ 17, 22, 9, 55, 13, 27, 39 };
            int i = Array.BinarySearch(A, 55);
            if (i >= 0)
                Console.WriteLine("Element Found At Index {0}", i);
            else
                Console.WriteLine("Element Was Not Found");
        }
    }
}

2. Clear(Array,Start,n) : 
Clears n number of elements starting from start in the given array i.e. those elements are set to the value 0. The following example clears 3 elements starting from index 2 in a one dimensional array of integers.

namespace Language
{
    class ArrayClear
    {
        static void Main()
        {
            int[] A ={ 10, 23, 17, 37, 61, 54, 9 };
            Array.Clear(A, 2, 3);
            Console.WriteLine("Elements In Array After Clear Are...");
            foreach (int n in A)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
        }
    }
}

3. Copy(S.Array,S.Index,D.Array,D.Index,n) : Copies n number of elements from S.Array starting from the index S.Index to D.Array starting from the index D.Index.

Copy(S.Array,D.Array,n) : This syntax copies first n number of elements from S.Array to D.Array.

The following example copies 3 elements from the array A starting from index 2 to the array B starting from the index 3.

namespace Language
{
    class ArrayCopy
    {
        static void Main()
        {
            int[] A ={ 1, 2, 3, 4, 5, 6, 7 };
            int[] B ={ 10, 20, 30, 40, 50, 60, 70 };
            //Array.Copy(A, 2, B, 3, 3);
            Array.Copy(A, B, 3);
            Console.WriteLine("Elements In Array B After Copy Are...");
            foreach (int n in B)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
        }
    }
}

4. IndexOf(Array,Element) : Searches for given element in given array using linear search technique and returns the index of first occurrence of that element in the array and other wise returns a negative value.

5. LastIndexOf(Array,Element) : Searches for given element in given array using linear search technique and returns the index of last occurrence of that element in the array and other wise returns a negative value.

Example : The following example searches for an element in a one dimensional array of integers using indexof and lastindexof methods.

namespace Language
{
    class ArrayIndexOf
    {
        static void Main()
        {
            int[] A ={ 25, 90, 52, 25, 17, 49, 25 };
            int i = Array.IndexOf(A, 25);
            int j = Array.LastIndexOf(A, 25);
            if (i >= 0)
                  Console.WriteLine("First Occurrence Was At Index {0}", i);
            else
                Console.WriteLine("Element Not Found");
            if (j >= 0)
                Console.WriteLine("Last Occurrence Was At Index {0}", j);
            else
                Console.WriteLine("Element Not Found");
        }
    }
}

6. Reverse(Array) : Reverses the elements in given array.
7. Sort(Array) : Sorts the elements in array in ascending order.

Example : The following example prints the elements in a one dimensional array in ascending and then in descending order.
namespace Language
{
    class ArraySort
    {
        static void Main()
        {
            int[] A ={ 23, 13, 17, 31, 9 };
            Array.Sort(A);
            Console.WriteLine("Elements In Ascending Order...");
            foreach (int n in A)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
            Array.Reverse(A);
            Console.WriteLine("Elements In Descending Order...");
            foreach (int n in A)
            {
                Console.Write("{0}\t", n);
            }
            Console.WriteLine();
        }
    }
}


Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

No comments:

Post a Comment