Menu
Coddy logo textTech

Declaring Arrays

Part of the Fundamentals section of Coddy's C++ journey — lesson 58 of 74.

An array is a collection of items, and it can contain values of the same type, such as numbers, strings, or even other arrays. Arrays are created using square brackets [], and the items inside the array are separated with commas.

Here is an example of how to create an array:

int numbers[] = {1, 2, 3, 4, 5};

To check the length of the array, we can use the std::size() operator:

int length = std::size(numbers)

The variable length will hold 5 because there are 5 elements in the array.

Another way to create an array using brackets [] followed by the array size:

int numbers[5];

Creates an array of 5 integers, all initialized to 0

challenge icon

Challenge

Easy

Create an array called shoppingList that contains the following items: bread, eggs, milk, and butter.

Cheat sheet

Arrays are collections of items of the same type, created using square brackets [] with items separated by commas:

int numbers[] = {1, 2, 3, 4, 5};

To get the length of an array, use std::size():

int length = std::size(numbers);

You can also create an array by specifying the size:

int numbers[5]; // Creates array of 5 integers, all initialized to 0

Try it yourself

#include <iostream>
#include <string>

int main() {
    // Create the shoppingList array here
    
    
    // Don't change the code below
    std::cout << "Shopping List:" << std::endl;
    for (int i = 0; i < std::size(shoppingList); i++) {
        std::cout << shoppingList[i] << std::endl;
    }
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals