๐ C++ Programming Lesson 14: Introduction to Arrays and Their Principles (Special Focus on int Type)

๐ Course Navigation
1ใ๐ค Why do we need arrays? (Scenarios of “batch storage” in life)2ใ๐ Definition and Initialization of int Type Arrays (3 common initialization methods)3ใโ๏ธ Array Index and Subscript: The “Key” to Accessing Data (Core rules and principles)4ใ๐งช Practical Case of int Arrays (From basic access to simple calculations)5ใโ ๏ธ Common Errors with Arrays and Tips to Avoid Them (Avoiding out-of-bounds and initialization pitfalls)6ใ๐ข Next Lesson Preview: Forward Traversal of Arrays (Reading Data from Front to Back)
1. ๐ค Why do we need arrays? โ From “Single Variable” to “Batch Storage”
In life, we often need to handle “a group of the same type of data”, for example:
- ๐ Statistics of 5 students’ math scores: 85, 92, 78, 95, 88;
- ๐ Recording prices of 3 products: 29, 58, 15;
- ๐ฎ Storing health points of 4 game characters: 100, 80, 120, 90.
If we use the single variables learned before, we would need to define score1, score2, score3, score4, score5 โ not only are the variable names repetitive, but it is also difficult to process them in bulk (for example, calculating the average score requires adding them one by one).
This is where we needarrays! It is like “a row of neat drawers”, each drawer stores one piece of data, and all drawers are managed under one name (like scores), allowing for easy “batch storage” and “batch access”. The int type array is specifically used to store integer data.
2. ๐ Definition and Initialization of int Type Arrays
The core of an array is “determining the type, name, and length”. The definition format for an int type array is:
int arrayName[arrayLength];
Where “arrayLength” must be apositive integer (indicating how many int type data can be stored). Initialization is the process of putting data into the array’s “drawers”, and there are 3 common methods:
(1) Complete Initialization: Specifying Values for All Elements
Directly write all data in order within curly braces, and the number of data must equal the array length:
#include <iostream>
using namespace std;
int main() {
// Define an int array of length 5 to store 5 students' scores (complete initialization)
int scores[5] = {85, 92, 78, 95, 88};
cout << "The score of the 3rd student: " << scores[2] << endl; // Later we will explain why it is [2]
return 0;
}
Output: The score of the 3rd student: 78
(2) Partial Initialization: Assigning Values to Only the First Few Elements
If the number of data in curly braces is less than the array length, the unassigned elements will be automatically initialized to 0:
int prices[3] = {29, 58}; // Length 3, first 2 elements are 29, 58, the 3rd element is automatically 0
cout << "The price of the 3rd product: " << prices[2] << endl; // Output 0
(3) Omitted Length Initialization: Letting the Compiler Automatically Calculate Length
If the array length is not specified, the compiler will automatically determine the length based on the number of data in curly braces (recommended for scenarios with a clear number of data):
int hp[] = {100, 80, 120, 90}; // The compiler automatically calculates the length as 4
cout << "Array length: " << sizeof(hp)/sizeof(int) << endl; // Output 4 (we will explain the calculation principle later)
Key Points to Note:
- Once the array length is determined, itcannot be modified (for example, after defining int scores[5], it cannot be changed to store 6 data);
- During initialization, the number of datacannot exceed the array length (for example, int scores[5] = {85, 92, 78, 95, 88, 100} will cause an error).
3. โ๏ธ Array Index and Subscript: The “Key” to Accessing Data
Each element of the array has a “number”, which is calledindex (also known as subscript), and it is the only way to access array elements. The core rule to remember is:
(1) The subscript starts from 0! Not from 1!
This is the most critical rule of arrays. For example, for the scores array of length 5, the correspondence between elements and subscripts is as follows:
|
Array Element |
scores[0] |
scores[1] |
scores[2] |
scores[3] |
scores[4] |
|
Stored Data |
85 |
92 |
78 |
95 |
88 |
|
Corresponding “Nth” Data |
1st |
2nd |
3rd |
4th |
5th |
In simple terms:The subscript of the nth element is n-1, for example, to access the “3rd student’s score”, you need to use scores[2].
(2) Two Operations for Subscript Access: Reading and Modifying
- Reading an Element: Get the element value through “arrayName[subscript]”;
- Modifying an Element: Change the element value through “arrayName[subscript] = newValue”.
Case demonstration:
#include <iostream>
using namespace std;
int main() {
int scores[5] = {85, 92, 78, 95, 88};
// 1. Reading an element: Get the score of the 4th student (subscript 3)
cout << "Before modification, the 4th student's score: " << scores[3] << endl; // Output 95
// 2. Modifying an element: Change the 4th student's score to 98
scores[3] = 98;
cout << "After modification, the 4th student's score: " << scores[3] << endl; // Output 98
return 0;
}
(3) Method to Calculate Array Length
Using sizeof(arrayName) can get the total byte size of the array, and sizeof(elementType) can get the byte size of a single element. Dividing the two gives the array length:
int hp[] = {100, 80, 120, 90};
// sizeof(hp): total byte size of the array (int occupies 4 bytes, 4 elements means 4*4=16 bytes)
// sizeof(int): byte size of a single int element (4 bytes)
int length = sizeof(hp) / sizeof(int);
cout << "Array length: " << length << endl; // Output 4
4. ๐งช Practical Case of int Arrays
Case 1: Traversing the Array and Printing All Elements
“Traversing” means accessing each element of the array one by one, and using a for loop (with known array length) is the most convenient:
#include <iostream>
using namespace std;
int main() {
int scores[5] = {85, 92, 78, 95, 88};
int length = sizeof(scores) / sizeof(int); // Calculate array length
cout << "All students' scores:";
// for loop: i from 0 to length-1 (covering all subscripts)
for (int i = 0; i < length; i++) {
cout << scores[i] << " "; // Print elements one by one
}
return 0;
}
Output: All students’ scores: 85 92 78 95 88
Case 2: Calculating the Average Value of Array Elements
While traversing the array, accumulate all elements and then divide by the array length (note to use double type to store the average value to avoid integer division):
#include <iostream>
using namespace std;
int main() {
int prices[3] = {29, 58, 15};
int length = sizeof(prices) / sizeof(int);
int sum = 0;
// 1. Accumulate all product prices
for (int i = 0; i < length; i++) {
sum += prices[i]; // Equivalent to sum = sum + prices[i]
}
// 2. Calculate average value (sum and length are int, convert to double to avoid integer division)
double average = (double)sum / length;
cout << "Total price of products: " << sum << endl; // Output 102
cout << "Average price of products: " << average << endl; // Output 34 (102/3=34)
return 0;
}
5. โ ๏ธ Common Errors with Arrays and Tips to Avoid Them
Error 1: Out-of-Bounds Index (The Most Dangerous Error!)
The array index must be between “0 ~ length – 1”. Exceeding this range is “out-of-bounds”, which can cause the program to crash or produce garbled output:
int scores[5] = {85, 92, 78, 95, 88};
// Error: Array length is 5, maximum index is 4, accessing scores[5] is out-of-bounds
cout << scores[5] << endl;
โ Correct: When traversing with a for loop, write the loop condition as i < length (length is the array length) to avoid exceeding the index of “length-1”.
Error 2: Number of Initial Data Exceeds Array Length
// Error: Array length is 5, but provided 6 data
int scores[5] = {85, 92, 78, 95, 88, 100};
โ Correct: Either reduce the number of data or increase the array length, or use “omitted length initialization” to let the compiler adapt automatically.
Error 3: Modifying Array Length (Array Length is Immutable!)
int scores[5] = {85, 92, 78, 95, 88};
// Error: Array length cannot be modified after definition
scores[5] = 100; // This is not "adding the 6th element", but out-of-bounds!
โ Correct: If more data needs to be stored, plan enough length in advance when defining the array, or learn about dynamic arrays later (for now, focus on fixed-length arrays).
Error 4: Direct Assignment of “Array Name” (Array Name is an Address, Cannot be Assigned Directly!)
int a[3] = {1, 2, 3};
int b[3];
// Error: Array names a and b are addresses, cannot be assigned directly using "="
b = a;
โ Correct: To assign values to an array, you need to assign each element one by one using a for loop:
for (int i = 0; i < 3; i++) { b[i] = a[i]; // Assign elements of a to b one by one}
6. ๐ข Next Lesson Preview: Reverse Traversal of Arrays (Reading Data from Back to Front)
In this lesson, we learned about the definition, initialization, and forward traversal of int arrays (from index 0 to index length-1), but in life, there are also scenarios of “processing data from back to front”:
- ๐ Printing student scores in reverse order (from the last student to the first);
- ๐ Searching for the first score greater than 90 starting from the end of the array;
- ๐งฎ Calculating the “reverse cumulative sum” of array elements (adding from the last element to the first).
These scenarios requirereverse traversal of arrays! In the next lesson, we will learn:
1. The core logic of reverse traversal: starting from “maximum index (length-1)” to “index 0”;2. The for loop syntax for reverse traversal: for (int i = length-1; i >= 0; i–);3. Practical cases: printing the array in reverse order, reverse searching for target elements, and reverse cumulative sum.
Once you master reverse traversal, your operations on arrays will be more flexible, allowing you to handle more “reverse processing” needs. Looking forward to exploring together in the next lesson! ๐
