C# Arrays
Objectives
- What is Arrays ?
- Types of arrays
- How to Declaring arrays
- Accessing array elements
- Array initialization
- Multidimensional arrays
What is Arrays ?
Arrays are data structures used to store a collection of elements of the same data type.
They provide a convenient way to work with multiple values of the same type under a single variable name.
Types of Arrays:
There are three main types of arrays:
- Single-Dimensional Arrays
- Multi-Dimensional Arrays
- Jagged Arrays
Arrays Type | Description | Example |
---|---|---|
Single-dimensional Arrays | A linear collection of elements of the same data type. | int[] numbers = {1, 2, 3, 4, 5}; |
Multi-Dimensional Arrays | Elements arranged in a grid-like structure with multiple dimensions. | int[,] matrix = {{1, 2, 3}, {4, 5, 6}}; |
Jagged Arrays | An array that holds arrays of different sizes. | string[][] jaggedArray = { new string[] {"A", "B"}, new string[] {"C", "D", "E"} }; |
Declaring arrays:
To declare an array in C#, you specify the data type of the elements followed by square brackets [] and the array name.
You can specify the size of the array within square brackets, or you can leave it empty for later initialization.
int[] numbers; // declaration of an integer array
Accessing Array Elements:
Array elements are accessed using zero-based indexing, where the index starts at 0 for the first element.
You access an element by specifying the array name followed by square brackets containing the index of the element you want to access.
int[] numbers = { 10, 20, 30, 40, 50 };
int firstElement = numbers[0]; // accessing the first element (10)
Array Initialization:
Arrays can be initialized when they are declared by providing a list of initial values enclosed in curly braces {}.
You can initialize the array elements individually after declaration.
int[] numbers = { 10, 20, 30, 40, 50 }; // initialization during declaration
Multidimensional Arrays:
Multidimensional arrays store elements in multiple rows and columns.
To declare a multidimensional array, you specify the data type of the elements followed by comma-separated lengths enclosed in square brackets [,].
Example:
int[,] matrix = new int[3, 3]; // declaration of a 3x3 integer matrix
Multidimensional arrays are accessed using multiple indices corresponding to the row and column positions.
Example:
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int element = matrix[1, 2]; // accessing element at row 1, column 2 (value: 6)