简体   繁体   中英

How can I assign array in a jagged array?

I have 3 sets of array they are: a[i], b[j], c[k] and I have to assign them to a jagged array for me to show them to the output.

array[0] = new int[3] { a[i] };
array[1] = new int[2] { b[j] };
array[2] = new int[2] { c[k] ];

for (i = 0; i < array.Length; i++)
{
     Console.Write("First Array: ");
     for (int l = 0; l < array[i].Length; l++)
     {
           Console.Write("\t" + array[i][l]);
     }

     Console.Write("Second Array: ");
     for (int m = 0; m < array[i].Length; m++)
     {
           Console.Write("\t" + array[i][m]);
     }

     Console.Write("Third Array: ");
     for (int n = 0; n < array[i].Length; n++)
     {
           Console.Write("\t" + array[i][n]);
     }

     Console.WriteLine();
}

But I couldn't make them work, they are always giving me an error.

In Javascript similary thing can be done by-


let a =  [ '1','2','3']
let b =  ['4','5']
let c =  ['6','7']

let array = []
array.push(a)
array.push(b)
array.push(c)
console.log(array)

output

[ [ '1', '2', '3' ], [ '4', '5' ], [ '6', '7' ] ]
int[] a = new int[] { 1, 2, 3 };
int[] b = new int[] { 4, 5 };
int[] c = new int[] { 6, 7, 8, 9 };

int[][] array = new int[][] { a, b, c };

That should probably look more like:

// place references to the source arrays into the jagged array
array[0] = a[i];
array[1] = b[j];
array[2] = c[k];

// iterate over the jagged array and output each array that is within
for (i = 0; i < array.Length; i++)
{
    Console.Write("Array " + i + ": ");
    for (int j = 0; j < array[i].Length; j++)
    {
        Console.Write("\t" + array[i][j]);
    }
    Console.WriteLine();
}

Note that we only have ONE inner for loop that is iterating over each inner array using the outer loop's i variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM