Array access
Learn to access and modify array elements by index.
Array access
You access array elements by index. Indices start at zero: nums[0] is the first, nums[1] the second. Writing nums[i] = 99; updates the element.
An out-of-range index (for example nums[5] on a three-element array) throws an IndexOutOfRangeException. So make sure the index stays inside the bounds before using it.
Updating an element
You can assign new values to array elements: nums[0] = 99; turns the first element into 99. The array's size stays fixed, but its contents can change.
For example, to update the first score on a scoreboard you write scores[0] = 100;. This changes the content but keeps the array length the same; no new elements can be added.
Exercise Update the first element and print it
Declare a nums array with the value { 1, 2, 3 }. Update the first element with nums[0] = 10;. Then print nums[0] with Console.WriteLine. The output should be 10.
Show example solution
Write int[] nums = { 1, 2, 3 }; nums[0] = 10; Console.WriteLine(nums[0]);
Example solution:
using System;
class Program
{
static void Main()
{
int[] nums = { 1, 2, 3 };
nums[0] = 10;
Console.WriteLine(nums[0]);
}
}
Test yourself
-
Write the index of the second element
int[] nums = {10, 20, 30}; int second = nums[____];Show answer
int[] nums = {10, 20, 30}; int second = nums[1]; -
With int[] nums = {10, 20, 30}; what is nums[1]?
int[] nums = {10, 20, 30}; Console.WriteLine(nums[1]);- 10
- 20
- 30
- Error
Show answer
20 — Correct. nums[1] gives 20, the second element.
-
Match each index to its value
- nums[0]
- First element
- nums[1]
- Second element
- nums[2]
- Third element
- nums.Length - 1
- Last element