C++: Array Basics

Last updated: 2026-08-26

In previous lessons, each variable could only store one value.

But if you need to store 100 students' scores, you can't declare 100 variables, right?

Arrays solve this problem — a contiguous block of memory used to store multiple values of the same type.



1. What is an Array?

(1) 1.1 Arrays in Everyday Life

Real-life Analogy Program Equivalent
A row of mailboxes (each with a different number) Array (each element has a different index)
A carton of eggs (12 eggs, numbered 1-12) Array (12 elements, indices 0-11)

Characteristics of arrays:

  1. All elements are the same type (all int, or all double)
  2. Contiguous memory (elements are stored one after another)
  3. Indices start from 0 (not from 1!)

(2) 1.2 Why Do We Need Arrays?

Without arrays (bad example):

▶ Example 2: Basic Programming Practice (Difficulty ⭐)

CPP
#include <iostream>

int main() {
 int score1 = 90;
 int score2 = 85;
 int score3 = 92;
 // ... need to declare 100 variables!

 return 0;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
(Program output)

With arrays (good example):

CPP
#include <iostream>

int main() {
 int scores[100]; // array that can hold 100 integers

 // use loop to assign values
 for (int i = 0; i < 100; i++) {
 scores[i] = 0;
 }
 
 return 0;
}


2. Array Declaration and Initialization

(1) 2.1 Declaring an Array

Syntax:

TEXT 📖 Display only
Type arrayName[Number of elements];

Example:

CPP
int scores[5]; // array that can hold 5 integers
double prices[10]; // array that can hold 10 doubles
char letters[26]; // array that can hold 26 chars

💡 Key point: Array indices start from 0, so scores[5] has indices from 0 to 4 (not 1 to 5).

(2) 2.2 Initializing an Array

Method 1: Initialize at declaration

TEXT 📖 Display only
int scores[5] = {90, 85, 92, 78, 88};

Method 2: Partial initialization

CPP
int scores[5] = {90, 85}; // only initialize first two, rest become 0 automatically

Method 3: Let the compiler infer the size

CPP
int scores[] = {90, 85, 92, 78, 88}; // compiler infers size as 5

💡 Tip: Method 3 is recommended — if you change the array contents later, you don't need to manually update the size.



3. Accessing Array Elements

(1) 3.1 Reading Elements

Syntax:

TEXT 📖 Display only
arrayName[Index]

Example:

CPP
#include <iostream>

int main() {
 int scores[5] = {90, 85, 92, 78, 88};
 
 std::cout << "First score: " << scores[0] << std::endl; // 90
 std::cout << "Third score: " << scores[2] << std::endl; // 92
 std::cout << "Last score: " << scores[4] << std::endl; // 88
 
 return 0;
}

(2) 3.2 Modifying Elements

CPP
#include <iostream>

int main() {
 int scores[5] = {90, 85, 92, 78, 88};
 
 scores[1] = 95; // change second score to 95
 std::cout << "Modified second score: " << scores[1] << std::endl; // 95
 
 return 0;
}


4. Traversing an Array

(1) 4.1 Traversing with a for Loop

CPP
#include <iostream>

int main() {
 int scores[5] = {90, 85, 92, 78, 88};
 
 std::cout << "All scores: " << std::endl;
 for (int i = 0; i < 5; i++) {
 std::cout << "No. " << i + 1 << " Score: " << scores[i] << std::endl;
 }
 
 return 0;
}

💡 Key point: When traversing an array, the loop condition is typically i < array_size, rather than i <= array_size - 1 (which is more error-prone).



5. Array Size

(1) 5.1 Calculating the Number of Elements with sizeof

CPP
#include <iostream>

int main() {
 int scores[5] = {90, 85, 92, 78, 88};
 
 int size = sizeof(scores) / sizeof(scores[0]); // calculate array size
 std::cout << "Array size:" << size << std::endl; // 5
 
 return 0;
}

How it works:

💡 Tip: This method only works for actual arrays, not pointers (covered later).



6. Arrays as Function Parameters

(1) 6.1 The Problem: Arrays Decay into Pointers

When you pass an array to a function, it decays into a pointer (losing size information).

CPP
#include <iostream>

// array as parameter, need to pass size
void printArray(int arr, int size) {
 for (int i = 0; i < size; i++) {
 std::cout << arr[i] << " ";
 }
 std::cout << std::endl;
}

int main() {
 int scores[5] = {90, 85, 92, 78, 88};
 printArray(scores, 5); // pass array name (which is address of first element)
 return 0;
}

💡 Key point: When passing an array as a parameter, you must also pass the size.



7. Common Errors

(1) 7.1 Array Out of Bounds

Error example:

CPP
#include <iostream>

int main() {
 int scores[5] = {90, 85, 92, 78, 88};
 
 std::cout << scores[5] << std::endl; // ERROR: out of bounds! max index is 4
 
 return 0;
}

Consequence: Reading garbage values, or program crash.

💡 Tip: C++ does not automatically check array bounds! This is one reason C++ is fast, but also a common source of bugs.

(2) 7.2 Using a Variable as Array Size (Before C++11)

Error example (before C++11):

CPP
#include <iostream>

int main() {
 int n = 5;
 int scores[n]; // ERROR (before C++11): array size must be compile-time constant
 
 return 0;
}

Correct approach (supported after C++11):

CPP
#include <iostream>

int main() {
 int n = 5;
 int scores[n]; // OK (after C++11): Variable Length Array (VLA) supported
 
 return 0;
}

💡 Better approach: Use std::vector (covered later), which supports dynamic sizes.



8. Practice: Calculating the Average Score

▶ Example 1: Calculating Average Score (Difficulty ⭐⭐)

CPP
#include <iostream>
#include <iomanip>

int main() {
 int scores[5] = {90, 85, 92, 78, 88};
 int sum = 0;
 
 // calculate total score
 for (int i = 0; i < 5; i++) {
 sum += scores[i];
 }

 // calculate average score
 double average = static_cast<double>(sum) / 5;
 
 std::cout << std::fixed << std::setprecision(2);
 std::cout << "Total: " << sum << std::endl;
 std::cout << "Average: " << average << std::endl;
 
 return 0;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Total: 433
Average: 86.60

❓ FAQ

Q How do I initialize all array elements to 0?
A > > int scores[100] = {0}; // Method 1: Partial initialization(remaining auto-fill with 0) > > int scores[100]; > for (int i = 0; i < 100; i++) { > scores[i] = 0; // Method 2: Assign with loop > } >

▶ Example 3: Array Traversal (Difficulty ⭐)

CPP
#include <iostream>

int main() {
    int scores[] = {85, 92, 78, 90, 88};
    int sum = 0;

    for (int i = 0; i < 5; i++) {
        sum += scores[i];
    }

    double avg = sum / 5.0;
    std::cout << "Average: " << avg << std::endl;

    return 0;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Average: 86.6
💡 Tip: Arrays can be initialized with {}, and the number of elements can be calculated using sizeof(arr) / sizeof(arr[0]).


📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Declare a double array to store 5 prices, then use a loop to calculate the total price.

  2. Intermediate (Difficulty ⭐⭐): Write a function int findMax(int arr, int size) that finds the maximum value in an array. Test it in main.

  3. Challenge (Difficulty ⭐⭐⭐): Write a program that lets the user enter 10 integers, stores them in an array, then:

  4. Finds the maximum and minimum values

  5. Calculates the average score

  6. Outputs all scores above the average


13. 🚀 Next Step

Now that you've learned array basics, let's move on to Multi-dimensional Arrays (Lesson 17) — handling tabular data (such as matrices, game boards).

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏