C# array of arrays

To create an array of arrays or jagged array, you need to specify only the size of upper level array when new keyword is used to allocate the upper level array. Then lower level arrays are also allocated with the new keyword.

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

namespace Csharp
{

   class Program
   {
    
     static void Main(string[] args)
     {
      
           int[][] arr = new int[5][]; //allocate upper level array
           int i, j;
           for (i = 0; i < arr.Length; i++)
               for (j = 0; j < 5; j++) //allocate lower level arrays
                arr[i] = new int[5];
           //assign elements to the arrays
           for (i = 0; i < arr.Length; i++)
             for (j = 0; j < arr[i].Length ; j++)
             {
                if (i == j) arr[i][j] = 0;
                else if (i > j) arr[i][j] = 1;
                else arr[i][j] = -1;
             }
        //read elements of the arrays
           for (i = 0; i < arr.Length; i++)
           {
             for (j = 0; j < arr[i].Length; j++)
                Console.Write("{0}\t", arr[i][j]);
             Console.WriteLine();
           }
        Console.Read();

     }
}
}

To create stretchable array of arrays, use ArrayList:
-Use one ArrayList as container
-Create many objects of ArrayList as you want and then add them to the container ArrayList
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Csharp
{

   class Program
   {
    
     static void Main(string[] args)
     {
        int i, j;
        ArrayList container = new ArrayList();
        ArrayList lspc0 = new ArrayList();
        ArrayList lspc1 = new ArrayList();
        ArrayList temp=null;
        //add item to arraylist lspc0
        lspc0.Add(10);
        lspc0.Add(20);
        //add item to arraylist lspc1
        lspc1.Add("C# programming");
        lspc1.Add("C++ programming");
        //arraylist lspc0 and lspc1 to container arraylist
        container.Add(lspc0);
        container.Add(lspc1);
        //then we have array of arrays

        for (i = 0; i < container.Count; i++)
        {
           temp = (ArrayList)container[i];
           for (j = 0; j < temp.Count; j++)
             Console.WriteLine(temp[j]);
        }
        Console.Read();

     }
}
}

Posted by: Ly | post date: 01-25-2013 | Subject: C# Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.