cpp / beginner
Snippet
Accessing Array Elements
Arrays store multiple values of the same type in contiguous memory. Access elements using square brackets with a zero-based index. Index 0 gives the first element, index 2 gives the third. Arrays are mutable - you can change values after creation.
snippet.cpp
1
2
3
4
5
6
7
8
#include <iostream>int main() {int numbers[] = {10, 20, 30, 40, 50};std::cout << "Third element: " << numbers[2] << std::endl;numbers[0] = 100;std::cout << "First element now: " << numbers[0] << std::endl;return 0;}
Breakdown
1
int numbers[] = {10, 20, 30, 40, 50};
Declares and initializes an array of 5 integers
2
numbers[2]
Accesses the third element using index 2 (zero-based indexing)
3
numbers[0] = 100;
Modifies the first element by assigning a new value to index 0