Curriculum
An array is a collection of elements of the same data type in C#. Arrays provide a convenient way to store and access a group of related values.
To declare an array in C#, you must specify the data type of the array and the number of elements it will contain. Here is an example of declaring an integer array with three elements:
int[] numbers = new int[3];
This creates an integer array called numbers
with three elements, which are initially set to 0. You can access the elements of the array using their index, which starts at 0. Here is an example of setting the values of the array elements:
numbers[0] = 1; numbers[1] = 2; numbers[2] = 3;
You can also initialize the values of the array elements when declaring the array, like this:
int[] numbers = new int[] {1, 2, 3};
Arrays can be used to store and manipulate large amounts of data, such as in mathematical calculations or in storing and accessing data from a database. They are also commonly used in algorithms and data structures, such as sorting and searching algorithms.
Here is an example of using an array to calculate the average of a set of numbers:
int[] numbers = new int[] {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i < numbers.Length; i++) { sum += numbers[i]; } double average = (double)sum / numbers.Length; Console.WriteLine("The average of the numbers is {0}", average);
This code first declares an integer array with five elements and initializes its values. Then it calculates the sum of the array elements using a loop that iterates through the array using its Length
property. Finally, it calculates the average of the array elements and prints it to the console.
Arrays are a powerful tool in C# for working with collections of data, and are essential to many programming tasks.