Arrays
In the world of programming, arrays are like a container that can hold multiple values of the same data type. Imagine arrays as a row of numbered boxes, where each box can store a value.
Arrays in C# are fixed in size, meaning you need to specify the size of the array when declaring it. Once the array is created, you can access and modify the elements by their index.
To declare an array in C#, you need to specify the data type followed by square brackets []
, and then the name of the array. Here's an example:
1int[] numbers = { 1, 2, 3, 4, 5 };
In this example, we declared an array called numbers
that can store integers. We also assigned values to the array using the array initializer syntax.
To access an element in an array, you can use the index of the element. Remember that the index starts from 0. Here's an example:
1int firstElement = numbers[0];
2Console.WriteLine("The first element is: " + firstElement);
This code will output The first element is: 1
.
Arrays also have a Length
property that gives you the number of elements in the array. Here's an example:
1Console.WriteLine("The size of the array is: " + numbers.Length);
This code will output The size of the array is: 5
.
You can also loop over the elements in an array using the foreach
loop. Here's an example:
1Console.WriteLine("The elements in the array are:");
2foreach (int num in numbers)
3{
4 Console.WriteLine(num);
5}
This code will output each element of the numbers
array on a new line.
Arrays are a powerful tool in programming as they allow you to store and manipulate multiple values in a single variable. They are commonly used in various algorithms and data structures.
xxxxxxxxxx
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine("The size of the array is: " + numbers.Length);
Console.WriteLine("The elements in the array are:");
foreach (int num in numbers)
{
Console.WriteLine(num);
}