Home » .Net

Two dimensionals arrays in C#

Learn: Two dimensionals arrays in C#.Net, how they declared, read and print? How to initialize a two dimensionals array in C#.Net?

Before reading ahead, I would recommend to read: One (Single) Dimensional Arrays in C#.

In Single Dimensional Array, we were able to store elements in a single dimension (Array elements were store contiguous).

If we need to store data in a tabular like format, we cannot do this using single (one) dimensional array.

In two dimensionals arrays, we can store more than one dimension for arrays in C#. Two dimensionals array stores data in tabular form.

Here, first dimension specifies number of rows and second specifies number of columns.

Syntax of single dimensional array:

<data_type>[,] variable_name = new <data_type>[SIZE]; 

Example:

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

Here, new operator is used to allocate memory space for the array. Total number of rows will be 2 and columns 3. Thus, space for 3*2 = 6 integer elements will be created.

Initialization of single dimensional array:

int[,] X = {{1,2},{3,4},{5,6}};  

Consider the program:

using System;

namespace arrayEx
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            int j = 0;
            int[,] X;

            X = new int[2,3];

            Console.Write("Enter Elements : \n");
            for (i = 0; i < 2; i++)
            {
                for (j = 0; j < 3; j++)
                {
                    Console.Write("\tElement[" + i + ","+j+"]: ");
                    X[i, j] = Convert.ToInt32(Console.ReadLine());
                }
            }

            Console.Write("\n\nElements are: \n");
            for (i = 0; i < 2; i++)
            {
                for (j = 0; j < 3; j++)
                {
                    Console.Write(X[i, j] + " ");
                }
                Console.WriteLine();
            }

        }
    }
}

Output

Enter Elements :      
        Element[0,0]: 10
        Element[0,1]: 20
        Element[0,2]: 30
        Element[1,0]: 40
        Element[1,1]: 50
        Element[1,2]: 60
 
 
Elements are:         
10 20 30              
40 50 60
Press any key to continue . . .
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.