MenuHeader

Wednesday 28 February 2024

Arrays in C# || C# full course || basics in C# || ABFirstTech

                               Arrays in C#


Arrays in C# are used to store collections of elements of the same data type. C# supports single-dimensional arrays, multidimensional arrays, and jagged arrays.

1. Single-Dimensional Array:

A single-dimensional array is a collection of elements stored in a linear sequence. It is declared with a specified data type, followed by square brackets []:

int[] numbers = new int[5]; // Declare an integer array of size 5

You can initialize and access elements like this:
numbers[0] = 1; numbers[1] = 2; // ... int thirdElement = numbers[2];

2. Multidimensional Array:

A multidimensional array is an array of arrays. Commonly used are two-dimensional arrays, but you can have arrays with more dimensions.

Two-Dimensional Array:

int[,] matrix = new int[3, 4]; // Declare a 2D array of size 3x4

You can initialize and access elements as follows:

matrix[0, 0] = 1; matrix[0, 1] = 2; // ... int value = matrix[1, 2];

Three-Dimensional Array:

int[,,] cube = new int[2, 3, 4]; // Declare a 3D array of size 2x3x4

3. Jagged Array:

A jagged array is an array of arrays where each element can be an array of different sizes.

int[][] jaggedArray = new int[3][];

You need to initialize each sub-array separately:
jaggedArray[0] = new int[] { 1, 2, 3 }; jaggedArray[1] = new int[] { 4, 5 }; jaggedArray[2] = new int[] { 6, 7, 8, 9 };
Accessing elements:
int value = jaggedArray[1][0]; // Accessing the first element of the second sub-array

Jagged arrays are flexible and allow different lengths for each row.

Arrays in C# are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. Array elements are accessed using square brackets [].


No comments:

Post a Comment

Angular Interview Questions and Answers 2024 (Real interview) | Angular 18

real time angular interview questions and answers realtime angular interview questions and answers, Top Angular Interview Questions, angular...