Arrays - in COBOL and C# and VB.NET

C# COBOL VB.NET
int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
{
   Console.WriteLine(nums[i]);
}

// 5 is the size of the array
string[] names = new string[5];
names[0] = "David";
names[5] = "Bobby";   // Throws System.IndexOutOfRangeException
// C# can't dynamically resize an array.  Just copy into new array.
string[] names2 = new string[7];
Array.Copy(names, names2, names.Length); // or names.CopyTo(names2, 0);



float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;

int[][] jagged = new int[][] {
  new int[] {1, 2},
  new int[] {3, 4, 5},
  new int[] {6, 7, 8, 9} };
jagged[0][4] = 5;
declare nums = table of binary-long (1 2 3)

declare names as string occurs 5
*> Can also do:
declare names-again as string occurs any
set size of names to 5

set names(1) to "David"  *> first element indexed as 1
*> ...but can also use zero based subscripting:
set names[0] to "David"  *> first element indexed as 0

*>set names(6) to "Bobby"  *> throws System.IndexOutOfRangeException

*> COBOL does not have direct resizing syntax but achieves similar
*> results using 'reference modification' syntax:
declare names2 as string occurs 7
set names2[0:size of names] to names
*> Resizing to a smaller size is even simpler:
set names2 to names[0:3]

declare twoD as float-short occurs any, any.
declare rows as binary-long = 3
declare cols as binary-long = 10
set size of twoD to rows, cols

declare jagged = table of (table of binary-long(1 2)
                           table of binary-long(3 4 5)
                           table of binary-long(6 7 8 9))

*> Can also do:
declare jagged2 as binary-long occurs any, occurs any
set size of jagged2 to 3
set size of jagged2(1) to 5
set jagged2(1 5) to 5
Dim nums() As Integer = {1, 2, 3}
For i As Integer = 0 To nums.Length - 1
   Console.WriteLine(nums(i))
Next

' 4 is the index of the last element, so it holds 5 elements
Dim names(4) As String
names(0) = "David"
names(5) = "Bobby"  ' Throws System.IndexOutOfRangeException

' Resize the array, keeping the existing values (Preserve is optional)
' Note, however, that this produces a new copy of the array --
' it is not an in-place resize!
ReDim Preserve names(6)




Dim twoD(rows-1, cols-1) As Single
twoD(2, 0) = 4.5

Dim jagged()() As Integer = {
  New Integer(2) {1, 2},
  New Integer(3) {3, 4, 5},
  New Integer(4) {6, 7, 8, 9}}
jagged(0)(4) = 5

Portions of these examples were produced by Dr. Frank McCown, Harding University Computer Science Dept, and are licensed under a Creative Commons License.