← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 1 of 15

C++ Arrays Introduction

What is an Array?

An array groups multiple values of the same data type under one variable name, stored back-to-back in contiguous memory, which is what makes accessing any element by its position both fast and predictable. This contiguous layout is the key difference between an array and other collection types that might scatter their elements across memory.

Example: What is an Array?

cpp
#include <iostream>

int main() {
	int scores[3] = {90, 85, 78};
	std::cout << scores[0] << " " << scores[1] << " " << scores[2] << std::endl;
	return 0;
}

Declaring and Initializing Arrays

You can declare and fill an array in a single statement using curly braces, like int scores[] = {90, 85, 78};, and if you omit the size in the brackets, the compiler automatically counts the initializer values to determine it. Specifying a size explicitly that's larger than your initializer list leaves the remaining elements zero-initialized.

Example: Declaring and Initializing Arrays

cpp
#include <iostream>

int main() {
	int scores[] = {90, 85, 78};
	std::cout << scores[0] << " " << scores[1] << " " << scores[2] << std::endl;
	return 0;
}

Accessing Array Elements

Array indexing is zero-based, meaning the first element sits at index 0 and the last at size - 1, not at size itself — attempting to access index size reads past the array's actual memory and produces undefined behavior rather than a helpful error. This off-by-one boundary is one of the most common sources of bugs in array-heavy code.

Example: Accessing Array Elements

cpp
#include <iostream>

int main() {
	int scores[] = {90, 85, 78};
	std::cout << "First: " << scores[0] << std::endl;
	std::cout << "Last: " << scores[2] << std::endl;
	return 0;
}

Modifying Array Elements

Assigning a new value directly to an indexed position, like scores[2] = 100;, permanently overwrites whatever was previously stored there — arrays don't preserve history, so once a value is replaced, the original is gone unless you saved it elsewhere first.

Example: Modifying Array Elements

cpp
#include <iostream>

int main() {
	int scores[] = {90, 85, 78};
	scores[2] = 100;
	std::cout << scores[2] << std::endl;
	return 0;
}

Looping Through Arrays

A standard indexed for loop or a range-based for loop can both walk through every element of an array in order; the indexed version additionally gives you the position of each element, which the range-based version does not expose directly. Choose the indexed form when you actually need to know *where* an element is, not just its value.

Example: Looping Through Arrays

cpp
#include <iostream>

int main() {
	int scores[] = {90, 85, 78};
	for (int i = 0; i < 3; i++) {
		std::cout << scores[i] << " ";
	}
	std::cout << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.