Accessing Elements
Part of the Fundamentals section of Coddy's C# journey — lesson 56 of 69.
In C#, we use arrays to store multiple values in a single variable. Each value in an array is called an element, and each element has an index. The indices start from 0 to the length of the array minus one. For example take a look at the next array:
char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};- Element
ais at index 0 - Element
bis at index 1 - ...
- Element
gis at index 6
To access an element of an array, we can use its index within square brackets. For example, to access the first element of an array named letters, we would use letters[0].
Here's an example:
int[] numbers = {10, 20, 30, 40, 50};
int element = numbers[2];The variable element will hold the value 30 because it accesses the third element (which has an index of 2).
Challenge
EasyCreate a method named Values that receives an array as an argument and prints all of the items in the array one after the other.
To iterate over an array use the .Length field:
for (int i = 0; i < numbers.Length; i++) {
// code
}This way i will iterate from 0 to numbers.Length (not including) which is exactly all of the array indices.
Cheat sheet
Arrays store multiple values in a single variable. Elements are accessed by index starting from 0:
char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
char element = letters[2]; // accesses 'c'To iterate over an array, use the .Length property:
for (int i = 0; i < numbers.Length; i++) {
// access numbers[i]
}Try it yourself
using System;
public class Program {
public static void Values(int[] arr) {
// Write code here
}
public static void Main(string[] args) {
int[] numbers = {10, 20, 30, 40, 50};
Values(numbers);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 311Arrays Basics
Declaring ArraysAccessing ElementsModifying ArraysArray MethodsRecap - Product ArrayEdit Recap - Reversed Array