Two Dimensional and Jagged Array in C#

Two Dimensional Array

This are array which stores the values in the form of rows and columns.

Syntax

<type>[,]<name>=new <type>[rows,cols];
Int[,] arr=new int[3,4];
-----------OR------------------
Int [,] arr;
Arr=new int[2,3];
-------- OR-------
Int [,] arr={list of values};

Eg

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace arrayDemo

{

    class _2DArray

    {

        int[,] arr = new int[4, 5];

        int r, c;

 

        public void accessarray()

        {

            Console.WriteLine("enter no of rows of array");

            r = int.Parse(Console.ReadLine());

            Console.WriteLine("enter no of columns of array");

            c = int.Parse(Console.ReadLine());

            Console.WriteLine("enter no of array Element");

 

            for (int i = 0; i < r; i++)

            {

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

                {

                    arr[i, j] = int.Parse(Console.ReadLine());

                }

            }

        }

        //printing the array

        public void printarray()

        {

            for (int i = 0; i < r; i++)

            {

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

                {

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

                }

                Console.WriteLine();

            }

        }

        public static void Main()

        {

            _2DArray obj = new _2DArray();

            obj.accessarray();

            obj.printarray();

            Console.ReadKey();

        }

    }

 

Assigning values to 2D array at the time of Declaration :-

Int [,] arr={
{11,12,13,14},
{21,22,23,24},
{31,32,33,34},
};

Jagged Array

This is also 2 D array but in case of 2D array all the rows should be having the same number of columns.

Whereas increase of jagged array the column size varies from row to row.

i.e. every row will be have different columns size.

Declaration of Jagged Array


<type>[ ][ ]<name>=new <type> [rows][ ];

Int [ ][] arr=new int [3] [ ];

---------------or----------
Int [ ][ ] arr={list of values};

While declaring a jagged array in its initial declaration we can only specify the number of rows to array.

After specify the no of rows the pointing to each rows .we need to specify the columns under the rows.

Eg

Int [] [] arr =new int [3][];
Arr[0]=new int [4];
Arr[1]=new int [2]
Arr [2]=new int [3]