C# Arrays
Terms
undefined, object
copy deck
- Are C# arrays 0-indexed or 1-indexed?
- C# arrays are 0-indexed.
- What .NET namespace contains the Array base class?
- System.Array
- Show a code snippet that declare an array of 10 integers.
- int[] intArray = new int[10];
-
Show a code snippet that references the last element of the following array.
int[] intArray = new int[5] -
int someInt = intArray[4].
Remember arrays in C# are 0-based. -
What is the value of the 3rd element in the following array?
int[] intArray = new int[5]; - 0 -- integers are defaulted to 0 if not otherwise assigned.
- Create an array of integers that is where the elements contain the values of the first 5 prime numbers.
-
int[] intArray = new int[5]
{1,2,3,5,7}; -
Create a string array containing the names of the months of the year.
Write a code snippet that extracts the name of the 5th month from the array. -
string[] theMonths = new string[]
{"Jan", "Feb", "Mar", "Apr", "May" ...}
string fifthMonth = theMonths[4]; -
Suppose that myClass is a public class. Consider the following snippet
myClass[] myArray = new myClass[5];
What is the value of myArray[3] immediately after the execution of this statement? - myArray[3] is null.
- Show a code snippet that passes an array that is initialized and passed in one step
-
...
CalcAverage(new int[] {1,2,3,4,5});
... - Write a code snippet that creates a multidimensional integer array of dimension 2x3.
- int[,] multiArray = new int[2,3];
- Suppose that you create an array variable but do not assign dimensions or initialize it. How do you assign values to it?
-
int[] intArray;
intArray = new int[] {1,2,3,4}; - Show a snippet that creates and initializes a 2x3 array in one statement.
-
int[,] intArray = new int[,]
{{1,2},{3,4},{5,6}}; - What is a "jagged" array?
- A "jagged" array is an array whose elements are also arrays.
- Write a snippet that creates an array with 3 elements that are 3,4,5 element integer arrays, respectively.
-
int[][] jaggedArray =
new int[3][];
jaggedArray[0] = new int[3];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[5]; - Write a code snippet that creates a jagged array with three elements that points to three multidimensional arrays.
-
int[][,] jaggedArray = new[3][];
jaggedArray[0] =
new int[,] {{1,2},{3,4}};
... - Show a simple example of how the "foreach" statement is used with arrays.
-
// initialized without use of 'new'
int[] intArray = {1,2,3,4,5};
foreach (int i in intArray)
{
Console.WriteLine("The value of the {0} element {1}.", i, intArray[i-1]);
}
Console.ReadLine();