Overview of Arrays

Arrays in Carbon are a collection of elements of the same data type, stored contiguously in memory. They provide a structured way to organize and manipulate multiple values of the same type.

Creating Arrays

Arrays are created using square brackets [], specifying the data type of the elements and the initial size of the array.

Code snippet

var numbers: [int] = [1, 2, 3, 4, 5];

Accessing Elements

Elements in an array are accessed using their index, starting from 0.

Code snippet

var firstNumber: int = numbers[0];

Modifying Elements

You can modify the value of an element by assigning a new value to its index.

Code snippet

numbers[2] = 10;

Array Length

The length of an array is determined by the number of elements it contains. You can access the length using the count property.

Code snippet

var arrayLength: int = numbers.count;

Iterating Over Arrays

You can iterate over the elements of an array using a for loop.

Code snippet

for element in numbers {
  print(element);
}

Array Slices

Array slices provide a way to create a new array from a portion of an existing array.

Code snippet

var subArray: [int] = numbers[1...3]; // Creates a new array with elements at indices 1, 2, and 3

Multidimensional Arrays

Carbon supports multidimensional arrays, which are arrays of arrays.

Code snippet

var matrix: [[int]] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

Key Points

  • Arrays are fixed-size collections of elements of the same data type.
  • Elements are accessed using their index.
  • Arrays can be iterated over using a for loop.
  • Array slices can be created to extract portions of an array.
  • Carbon supports multidimensional arrays.

Arrays are a fundamental data structure in Carbon, providing a versatile and efficient way to store and manipulate collections of data.

Pointers
Overview of Control Structures

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?