Array:
An array is a collection of elements of the same type stored in a contiguous memory location. It is handy for storing and manipulating multiple values of same datatypes.
Declaring an Array:
Array can be declared by specifying the data type of its elements followed by square brackets []
//Syntax:
data_type[] array_name;
//example:
int[] rollNum;
string[] names;
Initializing an Array:
Array can be initialized by specifying its size and assigning values to its elements. There are several ways to initialize an array:
-
Creating instance:
int[] numbers = new int[5]; // Creates an integer array with 5 elements int[] numbers = new int[n]; // Creates an integer array with n elements
-
Initializing with value:
int[] numbers = { 1, 2, 3, 4, 5 };
// Creates an integer array with 5 elements and initializes them
Accessing Array Elements:
Individual elements of an array can be accessed by using their index, starting from 0.
for eg:
int firstNumber = numbers[0]; // Accesses the first element (index 0)
int secondNumber = numbers[1]; // Accesses the second element (index 1)
Console.Write(numbers[0]); //print first element of array (index 0)
Modifying Array Elements:
Array can be modified by assigning new values to the elements of an array.
eg:
numbers[2] = 10; // Changes the value of the third element (index 2) to 10