Lec6 Arrays Lecture
Lec6 Arrays Lecture
Arrays
An array is a collection of variables of the same
type that are referred to by a common name.
Arrays are used for a variety of purposes because
they offer a convenient means of grouping together
related variables.
One-Dimensional Arrays (1/2)
A one-dimensional array is a list of related
variables. Such lists are common in programming.
◦ For example, you might use a one-dimensional
array to store the account numbers of the active
users on a network.
◦ Another array might store the current batting
averages for a baseball team.
One-Dimensional Arrays (2/2)
type[ ] array-name = new type[size];
int[] sample;
sample = new int[10];
int[] nums = new int[] { 99, 10, 100, 18, 78, 23, 63,
9, 87, 49 };
int[] nums = { 99, 10, 100, 18, 78, 23, 63, 9, 87, 49 };
Multidimensional Arrays
A multidimensional array is an array that has
two or more dimensions, and an individual
int[][] jaggedArray3 =
{
new int[] { 3, 5, 7, },
new int[] { 1, 0, 2, 4, 6 },
new int[] {1, 2, 3, 4, 5, 6, 7, 8},
new int[] {4, 5, 6, 7, 8}
};
2D arrays with Jagged arrays
It is possible to mix jagged and multidimensional arrays
The following is a declaration and initialization of a single-
dimensional jagged array that contains two-dimensional array
elements of different sizes:
which displays the value of the element [1,0] of the first array
(value 5):
System.Console.Write("{0}", jaggedArray4[0][1, 0]);
Demonstration of jagged array of integers
1. using System;
2. namespace jagged_array
3. {
4. class Program
5. {
6. static void Main(string[] args)
7. {
8. // Declare the array of four elements:
9. int[][] jaggedArray = new int[4][];
10. // Initialize the elements:
11. jaggedArray[0] = new int[2] { 7, 9 };
12. jaggedArray[1] = new int[4] { 12, 42, 26, 38 };
13. jaggedArray[2] = new int[6] { 3, 5, 7, 9, 11, 13 };
14. jaggedArray[3] = new int[3] { 4, 6, 8 };
15. // Display the array elements:
16. for (int i = 0; i < jaggedArray.Length; i++)
17. {
18. System.Console.Write("Element({0}): ", i + 1);
19. for (int j = 0; j < jaggedArray[i].Length; j++)
20. {
21. System.Console.Write(jaggedArray[i][j] + "\t");
22. }
23. System.Console.WriteLine();
24. }
25. Console.ReadLine();
26. }
27. }
28. }
Output:
A jagged little summary.
◦ Jagged arrays are fast and easy to use once you
learn the syntax. Prefer them to 2D arrays when
performance is key. Be careful of excess memory
usage.
◦ We should be careful using methods like
GetLowerBound(), GetUpperBound, GetLength, etc.
with jagged arrays. Since jagged arrays are
constructed out of single-dimensional arrays, they
shouldn't be treated as having multiple dimensions
in the same way that rectangular arrays do.