Introduction to Arrays in C#
Array
In C#, an array is a data structure that stores a fixed-size sequence of elements of the same type. Arrays are widely used in programming for tasks that involve working with collections of data, such as storing a list of numbers, strings, or objects.
Example : int[] numbers = new int[5];
- An array always stores values of a single data type
- C# supports zero-based index values in an array
- Arrays have a fixed length, means that once your create an array with a specific size, you cannot change its size later, The size of an array is determined at the time of its declaration.
- Array declaration specifies the type of data
- Array name, basically it is an identifier
- Declaring an array does not allocate memory to the array
myarray[0] = 78;
myarray[2] =
4233;
myarray[3] = 3;
myarray[4] = 96;
Access Array Elements
You can use the index of the desired element within square brackets ([]) after the array variable.
An array index always starts at 0.
Example:
int[] numbers = { 1, 2, 3, 4, 5
};
// Accessing the first element
int firstNumber =
numbers[0]; // Value: 1
// Accessing the third element
int thirdNumber =
numbers[2]; // Value: 3
Accessing array using for loop
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
foreach (int item in numbers)
Console.WriteLine(item);
}
animals[0] = "Elephant";
foreach (string item in animals)
Console.WriteLine(item);
}
int[] numbers = { 1, 2, 3 };
Console.WriteLine("Old Value at index 0: " + numbers[0]);
// change the value at index 0
numbers[0] = 11;
//print new value
Console.WriteLine("New Value at index 0: " + numbers[0]);
0 comments:
Post a Comment
Do not enter spam link