Beginner 10 min

Arrays Basics

Learn to work with arrays - fixed-size collections that store multiple values of the same type in contiguous memory

Learn how to store multiple values of the same type in a single, contiguous block of memory using arrays.

A Simple Example

#include <iostream>

int main() {
    // Declare and initialize array with braces
    int scores[5] {95, 87, 92, 78, 88};

    // Access elements using zero-based indexing
    std::cout << "First score: " << scores[0] << "\n";
    std::cout << "Third score: " << scores[2] << "\n";

    // Modify an element
    scores[1] = 90;
    std::cout << "Updated second score: " << scores[1] << "\n";

    // Loop through all elements
    for (int i{0}; i < 5; ++i) {
        std::cout << "Score " << i << ": " << scores[i] << "\n";
    }

    return 0;
}

Breaking It Down

Array Declaration and Size

  • Syntax: type name[size] - declares a fixed-size array
  • Size must be a constant: Cannot use variables for array size in standard arrays
  • Example: int scores[5]; creates space for 5 integers
  • Remember: Array size is fixed at compile time and cannot change

Array Initialization

  • Initialize with braces: int arr[5] {10, 20, 30, 40, 50};
  • Partial initialization: int arr[5] {1, 2}; fills rest with zeros: {1, 2, 0, 0, 0}
  • Size inference: int arr[] {1, 2, 3}; automatically deduces size 3
  • Remember: Uninitialized arrays contain garbage values - always initialize

Zero-Based Indexing

  • First element: arr[0] is the first element, not arr[1]
  • Last element: In an array of size N, the last element is arr[N-1]
  • Valid range: For size 5, valid indices are 0, 1, 2, 3, 4
  • Remember: Accessing arr[5] when size is 5 is out of bounds

Accessing and Modifying Elements

  • Read: int x = scores[2]; gets the value at index 2
  • Write: scores[2] = 95; sets the value at index 2
  • No bounds checking: C++ doesn't check if index is valid at runtime
  • Remember: Out-of-bounds access causes undefined behavior

Why This Matters

  • Instead of creating separate variables for related data (score1, score2, score3...), arrays let you store collections efficiently.
  • Arrays are fundamental to processing lists of data, managing game inventories, storing student grades, handling image pixels, and countless other real-world programming tasks.

Critical Insight

The array name without brackets is actually a pointer to the first element. This means array[3] is the same as *(array + 3). Understanding this relationship is crucial for advanced C++ programming!

When you write scores[2], the computer calculates the memory address as: base_address + (2 * size_of_int). This is why array access is incredibly fast - it's just pointer arithmetic!

Best Practices

Always initialize arrays: Use int arr[5] {0}; to zero-initialize all elements. Uninitialized arrays contain random garbage values.

Use constants for array size: Define const int SIZE{5}; and use it consistently. This makes the code easier to maintain and prevents magic numbers.

Check loop bounds carefully: Use i < size not i <= size to avoid off-by-one errors. Remember arrays are zero-indexed.

Consider std::array for modern C++: For better safety and features, use std::array<int, 5> instead of raw arrays when possible.

Common Mistakes

Off-by-one errors: Using i <= size instead of i < size in loops causes out-of-bounds access. For size 5, valid indices are 0-4.

No bounds checking: C++ doesn't check if indices are valid at runtime. Accessing arr[100] when size is 5 causes undefined behavior.

Variable size limitation: Cannot use variables for array size: int n = 5; int arr[n]; is non-standard. Use std::vector for dynamic sizing.

Uninitialized arrays: int arr[5]; without initialization contains garbage. Always initialize: int arr[5] {0};

Array decay: When passing arrays to functions, they decay to pointers, losing size information. Pass the size separately.

Debug Challenge

This program has an off-by-one error when looping through the array. Click the highlighted line to fix it:

1 #include <iostream>
2
3 int main() {
4 int numbers[5] {10, 20, 30, 40, 50};
5
6 for (int i{0}; i <= 5; ++i) {
7 std::cout << numbers[i] << "\n";
8 }
9
10 return 0;
11 }

Quick Quiz

  1. What is the index of the last element in an array of size 10?
-1
11
9
10
  1. What does this initialization create: int arr[5] {1, 2};?
{1, 2, garbage, garbage, garbage}
Compilation error
{1, 2, 0, 0, 0}
{1, 2, 1, 2, 1}
  1. What happens when you access an array index that is out of bounds?
Compiler error
Throws an IndexOutOfBoundsException
Returns zero automatically
Undefined behavior - could crash or return garbage

Step Through the Code

Walk through the code step by step. Watch how variables change and see the program output at each line.

Lesson Progress

  • Fix This Code
  • Quick Quiz
  • Practice Playground - run once