Notifications
Clear all
Topic starter 01/08/2025 11:25 pm
C++ arrays are like organized shelves in memory where you can store multiple values of the same type under a single name. Let’s unpack how they work 🧠📦
🧱 Declaring an Array
int numbers[5];
- This creates an array named
numbers
that can hold 5 integers. - The size must be a constant and known at compile time.
🧪 Initializing an Array
You can assign values when you declare it:
int numbers[5] = {10, 20, 30, 40, 50};
Or let the compiler infer the size:
int numbers[] = {10, 20, 30};
Partial initialization fills the rest with zeros:
int numbers[5] = {1, 2}; // → [1, 2, 0, 0, 0]
🔍 Accessing Elements
Arrays are zero-indexed:
std::cout << numbers[0]; // First element
std::cout << numbers[4]; // Fifth element
You can also update values:
numbers[2] = 99;
🔁 Looping Through an Array
for (int i = 0; i < 5; i++) {
std::cout << numbers[i] << " ";
}
This prints all elements in the array.
🧬 Multidimensional Arrays
You can create arrays with more than one dimension:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Access like: matrix[1][2]
→ 6
⚠️ Things to Remember
- Array size is fixed once declared.
- Accessing out-of-bounds indices leads to undefined behavior.
- C++ doesn’t check bounds automatically—so be careful!