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() function:
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];At local scope (for example inside main()), this leaves the 5 elements uninitialized, so they hold indeterminate values. Write int numbers[5] = {}; to set them all to 0. Only static or global arrays are implicitly zero-initialized.
Challenge
EasyCreate an array called shoppingList that contains the following items: bread, eggs, milk, and butter.
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;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else