none
Size in Two dimensional array RRS feed

  • Question

  • Hello,

    How can I remove row and column in Display method? Can I have row and column in Arr variable without row and column parameter?

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Display(int[,] Arr,int row,int column)
            {
                for (int i = 0; i < row; i++)
                {
                    for (int j = 0; j < column; j++)
                    {
                        Console.Write($"{Arr[i,j]}  ");
                    }
                    Console.WriteLine();
                }
            }
            static void Main(string[] args)
            {
                Console.WriteLine("Enter Row");
                int Row = int.Parse(Console.ReadLine());
    
                Console.WriteLine("Enter Column");
                int Column = int.Parse(Console.ReadLine());
    
                int[,] myArray = new int[Row,Column];
    
                for (int i = 0; i < Row; i++)
                {
                    for (int j = 0; j < Column; j++)
                    {
                        Console.WriteLine($"Enter Element {i}{j}");
                        myArray[i, j] = int.Parse(Console.ReadLine());
                    }
                }
                Display(myArray,Row,Column);
            }
        }
    }
    

    Wednesday, October 16, 2019 3:19 PM

Answers

  • C#/.NET size information is available from the instance itself. You don't need a row/column parameter when working with arrays. The # of rows is available via the Length property. For a multi-dimensional array you have to get the length for each dimension using GetLength method or GetLowerBounds/GetUpperBounds depending upon your array. Unlike other languages C# supports both rectangular and jagged arrays. For rectangular arrays (like you have) GetLength is sufficient. If you had jagged arrays then you'd have to enumerate each row as each one could have a different length value.

    class Program
    {
        static void Main ( string[] args )
        {
            var arr = new int[10, 20];
    
            Display(arr);
        }
    
        static void Display (int[,] values )
        {
            Console.WriteLine($"Total Rows = {values.Length}");
            Console.WriteLine($"Rows = {values.GetLength(0)}");
            Console.WriteLine($"Columns = {values.GetLength(1)}");
        }
    }


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by Arash_89 Wednesday, October 16, 2019 7:22 PM
    Wednesday, October 16, 2019 5:29 PM
    Moderator