C++ One-Dimensional Arrays: Fundamentals and Basic Applications

1. Core Concepts

In C++, an array is a contiguous memory structure that stores a sequence of elements, all of the same data type.

1.1 Understanding Homogeneous Storage

The phrase "same type" means each element must conform to a uniform data type—such as int, float, or char. For instance, a collection cannot simultaneously hold integers and floating-point numbers unless cast or wrapped in a higher-level container.

1.2 Arrays as Structured Data

A variable is like a single labeled box storing one item. An array is a row of such boxes—indexed sequentially, starting at 0. This organized layout enables efficient access via subscript notation (e.g., element[index]).

Data structures can be broadly categorized as linear or nonlinear. Arrays belong to the linear group because their elements maintain a one-to-one sequential relationship.

2. Declaring and Initializing Arrays

2.1 Static Array Definition

Static arrays have fixed sizes determined at compile time:

dataType arrayName[capacity];

Example:

int scores[5];

This declares an array named scores capable of holding five int values.

2.2 Initialization Options

You may initialize elements during declaration:

int scores[5] = {95, 88, 76, 92, 90};

Or omit the size, letting the compiler infer it from the initializer list:

int scores[] = {95, 88, 76, 92, 90};

3. Array Element Access and Modification

Each element is referenced using zero-based indices:

  • Read: int topScore = scores[0]; retrieves the first score.
  • Write: scores[2] = 85; updates the third entry.

Always ensure your index stays within 0 ≤ index < capacity; otherwise, you trigger undefined behavior—a critical pitfall known as array overflow/underflow.

4. Traversing Arrays

A common pattern is using a loop to process all elements:

int count = 0;
for (int i = 0; i < n; ++i) {
    if (scores[i] >= 90) {
        ++count;
    }
}

This loop scans each score and tallies those ≥ 90.

5. Practical Example: Counting High Scores

Problem Description

Given a list of n exam scores, determine how many students scored at least 90 points.

Device Variables

int n;          // number of students
int list[100];  // max possible score entries
int result = 0; // counter for high scorers

Data Input

cin >> n;
for (int idx = 0; idx < n; ++idx) {
    cin >> list[idx];
}

Processing Logic

for (int j = 0; j < n; ++j) {
    if (list[j] >= 90) {
        ++result;
    }
}

Output & Full Code Snippet

#include <iostream>
using namespace std;

int main() {
    int n, list[100], result = 0;
    cin >> n;
    for (int k = 0; k < n; ++k) {
        cin >> list[k];
    }
    for (int idx = 0; idx < n; ++idx) {
        if (list[idx] >= 90) ++result;
    }
    cout << result << endl;
    return 0;
}

Thẻ: C++ array static-array linear-data-structure-indexing

Đăng vào ngày 23 tháng 5 lúc 00:23