TeachMate
My ProgressJoin Session

Arrays & Strings

0/12 completed · ~0h 58m

All Topics
C++LearnArrays & StringsSyllabus
1 / 12

Arrays

beginner
4 min read

What you'll learn

  • Explain why an array replaces many separate variables.
  • Declare an array and access elements with 0-based indices.
  • Traverse an array without reading out of bounds.

An array is a collection of elements of the same type stored in contiguous memory.

Problem

You must store the marks of 50 students. Declaring 50 separate variables does not scale:

Goal: Store many marks under one name so a single loop can process them.

int mark1, mark2, mark3;  // ... and 47 more

An array stores many values of the same type under one name, so a single loop can handle them all:

int marks[50];     // 50 marks under one name
marks[0] = 78;     // first student
marks[49] = 91;    // last student (index 49, not 50)

That is why arrays exist. The rest of this note shows how to declare, index, and traverse them.

Arrays and loops are the two biggest stuck points in an intro course. Spend extra time on 0-based indexing and have students trace a loop by hand before moving on.

Declaring Arrays

int scores[5];           // 5 integers (uninitialized)
int nums[5] = {1,2,3,4,5};  // Initialized
int zeros[5] = {};       // All zeros
int partial[5] = {1,2};  // {1,2,0,0,0}

Accessing Elements

int arr[5] = {10, 20, 30, 40, 50};
arr[0];   // 10 (first element)
arr[4];   // 50 (last element)
arr[5];   // OUT OF BOUNDS! Undefined behavior

Array Size

int arr[5] = {1, 2, 3, 4, 5};
sizeof(arr);       // 20 bytes (5 * 4 bytes per int)
sizeof(arr[0]);    // 4 bytes (size of one int)

// Modern C++ (preferred)
int size = std::size(arr);  // 5

// Or compute
int size = sizeof(arr) / sizeof(arr[0]);  // 5

Modifying Elements

int arr[5] = {1, 2, 3, 4, 5};
arr[0] = 100;   // {100, 2, 3, 4, 5}
arr[2] = 99;    // {100, 2, 99, 4, 5}

Common Mistakes

  • Array index out of bounds (no runtime check!)
  • Using variable index in C-style array: arr[i] is OK, but arr[n] where n is not constant is fine in C++
  • Forgetting arrays are 0-indexed
  • Comparing arrays: arr1 == arr2 doesn't work (compares addresses)

Debug

This loop is meant to print all 5 elements but reads one past the end: for (int i = 0; i <= 5; i++) cout << arr[i] << ' ';. Find and fix the bug.

Key takeaway: Arrays store same-type elements in contiguous memory — always check bounds and remember indices start at 0.

Try it: Declare an array of 5 scores, fill them with user input, and print the average.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects