C++ Programming Lesson 15: Forward and Backward Traversal of Arrays and Dynamic Assignment

๐Ÿš€ C++ Programming Lesson 15: Forward and Backward Traversal of Arrays and Dynamic Assignment

C++ Programming Lesson 15: Forward and Backward Traversal of Arrays and Dynamic Assignment

๐Ÿ“š Course Navigation

1ใ€๐Ÿค” Why Learn Array Traversal? (Traversal is the core foundation of array operations)2ใ€๐ŸŒŸ Forward Traversal of Arrays: Scanning Data from Front to Back (Basic Logic and Practical Application)3ใ€โšก Backward Traversal of Arrays: Reading Data from Back to Front (Core Techniques and Examples)4ใ€๐Ÿงฉ Dynamic Assignment: Allowing Arrays to “Real-Time Load Data” (Implementing Flexible Assignment with cin)5ใ€๐Ÿ“ฆ Comprehensive Case: Combining Forward and Backward Traversal with Dynamic Assignment (Solving Practical Problems)6ใ€โš ๏ธ Common Errors in Traversal and Assignment (Pitfall Guide)7ใ€๐Ÿ“ข Next Lesson Preview: Expandable Knowledge Points on One-Dimensional Arrays (Spoiler Alert)

1. ๐Ÿค” Why Learn Array Traversal? โ€” Traversal is the “Fundamental Skill” of Arrays

After an array stores a set of data, the most common operation is to “access each element one by one” โ€” for example, checking all student scores, calculating the total price of all products, or finding the highest score, all of which require “traversal” to achieve.

In simple terms:Without traversal, the data in the array is “dead data”, which cannot be used flexibly. Forward traversal (from the first to the last) and backward traversal (from the last to the first) are the two most basic and commonly used methods of array traversal. When combined with dynamic assignment (real-time input of data into the array), they can cover most array operation scenarios.

2. ๐ŸŒŸ Forward Traversal of Arrays: Scanning Data from Front to Back

Forward traversal starts “from array index 0 and accesses each index up to the last index (length-1)”, just like “checking from the first row of seats to the last row”; this is most intuitively combined with a for loop.

(1) Core Logic and Syntax

The three elements of traversal:

  • Start: Index starts from 0 (the first element);
  • End: Index goes up to length-1 (the last element);
  • Step: Index increments by 1 each time (moving forward one by one).

Syntax template:

int arr[5] = {10,20,30,40,50};int length = sizeof(arr)/sizeof(int); // Calculate array length// Forward traversal: i from 0 to length-1for (int i = 0; i < length; i++) {  // Operate on arr[i] (read, modify, etc.)  cout << "arr[" << i << "] = " << arr[i] << endl;}

(2) Practical Case: Counting Odd Numbers in an Array with Forward Traversal

Requirement: Define an int array, perform forward traversal, and count the number of odd numbers in it (odd numbers: those that leave a remainder of 1 when divided by 2).

#include <iostream>using namespace std;int main() {    int numbers[] = {7, 12, 9, 20, 15, 8};    int length = sizeof(numbers)/sizeof(int);    int oddCount = 0; // Count of odd numbers// Forward traversal of the array    for (int i = 0; i < length; i++) {// Check if the current element is odd        if (numbers[i] % 2 == 1) {            oddCount++;            cout << "Found odd number: " << numbers[i] << endl;        }    }    cout << "Total number of odd numbers in the array: " << oddCount << endl;    return 0;}

Running result:

Found odd number: 7
Found odd number: 9
Found odd number: 15
Total number of odd numbers in the array: 3

3. โšก Backward Traversal of Arrays: Reading Data from Back to Front

Backward traversal starts “from the last index of the array (length-1) and accesses each index down to index 0”, just like “checking from the last row of seats back to the first row”; the core is to adjust the start, end conditions, and step of the for loop.

(1) Core Logic and Syntax

The three elements of traversal:

  • Start: Index starts from length-1 (the last element);
  • End: Index goes down to 0 (the first element);
  • Step: Index decrements by 1 each time (moving backward one by one).

Syntax template:

int arr[5] = {10,20,30,40,50};int length = sizeof(arr)/sizeof(int);// Backward traversal: i from length-1 to 0for (int i = length - 1; i >= 0; i--) {    cout << "arr[" << i << "] = " << arr[i] << endl;}

(2) Practical Case: Finding the First Element Less Than 10 with Backward Traversal

Requirement: Define an int array, traverse backward, find the first element less than 10, and output it (stop traversal immediately after finding it to improve efficiency).

#include <iostream>using namespace std;int main() {    int scores[] = {15, 8, 22, 5, 18, 9};    int length = sizeof(scores)/sizeof(int);    bool found = false; // Flag to indicate if the target element is found// Backward traversal of the array    for (int i = length - 1; i >= 0; i--) {        if (scores[i] < 10) {            cout << "First element found backward that is less than 10: " << scores[i] << " (index: " << i << ")" << endl;            found = true;            break; // Exit the loop after finding        }    }    if (!found) {        cout << "No elements less than 10 in the array" << endl;    }    return 0;}

Running result:

First element found backward that is less than 10: 9 (index: 5)

4. ๐Ÿงฉ Dynamic Assignment: Allowing Arrays to “Real-Time Load Data”

Previously, arrays were “fixed values assigned at initialization” (e.g., int arr[] = {10,20,30}), but in practical scenarios, many data need to be “user input in real-time” (for example, inputting each student’s score during a statistics session), which requires “dynamic assignment” โ€” combining cin to assign values to array elements during traversal.

(1) Core Logic

  • First, define an empty array of specified length (or just define the length without initialization);
  • Use a for loop to traverse the array, getting user input with cin each time and assigning it to the current index element;
  • After assignment, the array stores the real-time data input by the user, which can be used for subsequent traversal.

(2) Practical Case: Dynamic Assignment to Store 5 Students’ Scores, Then Calculate Average with Forward Traversal

Requirement: Allow the user to input 5 students’ math scores, dynamically store them in an array, and then perform forward traversal to calculate the average score.

#include <iostream>using namespace std;int main() {    const int STUDENT_NUM = 5; // Number of students (defined with const for easy modification)    int scores[STUDENT_NUM]; // Define an array of length 5, uninitialized    int sum = 0;// Step 1: Dynamic assignment โ€” traverse the array, allowing user input for each student's score    cout << "Please enter the math scores for " << STUDENT_NUM << " students:" << endl;    for (int i = 0; i < STUDENT_NUM; i++) {        cout << "Score for student " << (i + 1) << ":";        cin >> scores[i]; // Dynamic assignment to the current index element    }// Step 2: Forward traversal of the array, accumulating scores to calculate average    for (int i = 0; i << STUDENT_NUM; i++) {        sum += scores[i];    }    double average = (double)sum / STUDENT_NUM; // Convert to double to avoid integer division    cout << "Average score of the 5 students: " << average << endl;    return 0;}

Running scenario:

Please enter the math scores for 5 students:
Score for student 1: 85
Score for student 2: 92
Score for student 3: 78
Score for student 4: 95
Score for student 5: 88
Average score of the 5 students: 87.6

5. ๐Ÿ“ฆ Comprehensive Case: Combining Dynamic Assignment with Forward and Backward Traversal

Requirement: The user inputs 6 integers, dynamically stores them in an array, then first performs forward traversal to print all elements, and then backward traversal to calculate the sum of all elements, finally outputting the sum.

#include <iostream>using namespace std;int main() {    const int ARRAY_LENGTH = 6;    int arr[ARRAY_LENGTH];    int sum = 0;// 1. Dynamic assignment: User inputs 6 integers    cout << "Please enter " << ARRAY_LENGTH << " integers:" << endl;    for (int i = 0; i << ARRAY_LENGTH; i++) {        cout << "Integer " << (i + 1) << ":";        cin >> arr[i];    }// 2. Forward traversal: Print all elements    cout << "Forward traversal of array elements:";    for (int i = 0; i << ARRAY_LENGTH; i++) {        cout << arr[i] << " ";    }    cout << endl;// 3. Backward traversal: Calculate the sum    for (int i = ARRAY_LENGTH - 1; i >= 0; i--) {        sum += arr[i];    }    cout << "Sum of all elements in the array (calculated with backward traversal): " << sum << endl;    return 0;}

Running result:

Please enter 6 integers:
Integer 1: 10
Integer 2: 20
Integer 3: 30
Integer 4: 40
Integer 5: 50
Integer 6: 60
Forward traversal of array elements: 10 20 30 40 50 60
Sum of all elements in the array (calculated with backward traversal): 210

6. โš ๏ธ Common Errors in Traversal and Assignment

Error 1: Incorrect starting index in backward traversal (written as length instead of length-1)

// Error: The maximum index of the array is length-1, length is an out-of-bounds indexfor (int i = length; i >= 0; i--) {  cout << arr[i] << endl; // First access arr[length], out of bounds!}

โœ… Correct: The starting index must be length – 1, i.e., for (int i = length – 1; i >= 0; i–).

Error 2: Using a variable (not const) to define array length during dynamic assignment

In C++, the array length must be a “compile-time constant” and cannot be defined using a regular variable (like a user input variable):

// Error: n is a regular variable and cannot be used to define array lengthint n;cin >> n;int arr[n]; // Compilation error!

โœ… Correct: Use const to define a fixed length (e.g., const int n = 5; int arr[n];), or learn about dynamic arrays (vector) later.

Error 3: Index out of bounds when modifying array elements during traversal

int arr[3] = {1,2,3};int length = 3;// Error: i from 0 to length, last time i=3, arr[3] is out of boundsfor (int i = 0; i <= length; i++) {  arr[i] = arr[i] * 2;}

โœ… Correct: Use i < length in the loop condition to ensure the index does not exceed length – 1.

7. ๐Ÿ“ข Next Lesson Preview: Expandable Knowledge Points on One-Dimensional Arrays

In this lesson, we mastered the forward and backward traversal of arrays and dynamic assignment, but there are many practical knowledge points about one-dimensional arrays that can be explored further. The next lesson can focus on the following directions to help you comprehensively master one-dimensional arrays:

  1. Common Algorithm Operations on Arrays:
  • Finding the maximum/minimum value in an array (e.g., “finding the highest score from the student scores array”);
  • Sorting array elements (simple sorting: bubble sort, selection sort, e.g., “sorting the scores array from highest to lowest”);
  • Searching for array elements (in addition to backward search, can also implement “finding the index by value”, e.g., “finding the index of the student with a score of 95”).
  1. Advanced Batch Operations on Arrays:
  • Copying arrays (in addition to assigning each element, can also implement “copying all elements from array A to array B” using traversal);
  • Concatenating arrays (e.g., “merging elements from array A and array B into array C”);
  • Removing duplicates from arrays (e.g., “deleting duplicate elements from an array containing repeated numbers, keeping only unique elements”).
  1. Combining Arrays with Functions:
  • Passing arrays as function parameters (e.g., “defining a function that receives an array and its length, returning the average of the array”);
  • Returning arrays from functions (note that in C++, functions cannot directly return arrays; this must be done indirectly using pointers or array names, which will be explained in detail later).

These knowledge points will help you solve more complex problems with arrays (e.g., “sorting and ranking student scores” and “removing duplicates and counting product prices”). In the next lesson, we will start with “finding the maximum value in arrays and simple sorting” to further enhance our array operation skills. ~๐Ÿ˜‰

C++ Programming Lesson 15: Forward and Backward Traversal of Arrays and Dynamic Assignment

Leave a Comment