7/24/2010

C# Array (Multidimensional Array)



Multidimensional Array:
Contains rows and columns.
syntax:
        data_type[,] array_name = new data_type[row_size,column_size];
example:  
        int m=2,n=2;
        int[,] a = new int[m,n];

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Arrays
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the size of the matrix");
            int m = int.Parse(Console.ReadLine());
            int n = int.Parse(Console.ReadLine());

            Console.WriteLine("Matrix Size: " + m + " X " + n);

            int[,] a = new int[m, n];


            Console.WriteLine("Enter " + (m * n) + " elements");
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                    a[i, j] = int.Parse(Console.ReadLine());

            Console.WriteLine("Matrix" +"\n"+ "--------");

            //GetLength(0) return number of rows.        
            for (int i = 0; i < a.GetLength(0); i++)
            {

                //GetLength(1) returns number of columns.
                for (int j = 0; j < a.GetLength(1); j++)
                {
                    Console.Write(a[i, j] + "\t");
                }
                Console.WriteLine();

               
            }
            //Rank returns dimension of an array.    
            Console.WriteLine("Rank of a Matrix: " + a.Rank);
        }
    }
}

No comments:

Post a Comment