Lesson 61 +10 XP

Arrays

Arrays

An array is a collection of values all under one name, each stored in its own "slot".

What is an array?

Think of a row of lockers. An array is a fixed-size row of boxes, all the same type, numbered from 0.

Declaring an array

int myNumbers[] = {25, 50, 75, 100};

This creates an array of four integers.

Accessing elements

The first element is at index 0. Use square brackets:

printf("%d\n", myNumbers[0]);  // 25

Changing an element

myNumbers[0] = 33;   // now myNumbers[0] is 33

Declaring with a size

You can state the size upfront:

int myNumbers[4] = {25, 50, 75, 100};

Indexes start at 0

The first element is [0], the last is size-1. Element 1 of your array is the SECOND value.

TL;DR

  • An array holds many values of one type.
  • Indexes start at 0.
  • Access with arr[i], like myNumbers[0].
  • The last index is size-1.