PROJECTENGRAM

TRAVERSING ARRAYS

Traversing Arrays

Tags: #◇CCPROG2 #◇C Programming #◇Programming #◇Computer Science #◇Data Structures #◇Data Types #◇Algorithms #◇Structured Programming #◇Memory Management


◇Overview

Traversing an array means visiting each element sequentially, typically using a loop.

◇Key Concepts

for loop is the most common traversal method while and do-while can also traverse arrays Pointer arithmetic provides an alternative traversal 2D arrays require nested loops

◇Details / Theory

For Loop Traversal

『』
C
int arr[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
    printf("%d ", arr[i]);
}
// Output: 10 20 30 40 50

Pointer-Based Traversal

『』
C
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;
for (int i = 0; i < 5; i++) {
    printf("%d ", *(p + i));
}

Traversal for Aggregation

『』
C
int arr[5] = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i < 5; i++) {
    sum += arr[i];
}
printf("Sum: %d\n", sum);  // Sum: 150

2D Array Traversal

『』
C
int matrix[3][4];
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        printf("%d ", matrix[i][j]);
    }
    printf("\n");
}

Common Traversal Patterns

PatternDescription
Linear scanVisit every element once
Reverse traversalfor (i = n-1; i >= 0; i--)
Conditional skipProcess only elements matching a condition
SearchStop when target found

◇Common Pitfalls

Off-by-one errors: using <= instead of < in the loop condition. Forgetting to pass array size to functions — cannot compute it from a pointer. Modifying the loop variable inside the loop body.

◇Summary

TL;DR — Array traversal visits each element using loops or pointer arithmetic. for loops are most common. 2D arrays need nested loops. Always respect bounds to avoid undefined behavior.

Related: ◇Accessing Elements — ◇Size — ◇Arrays and Pointers — ◇One-Dimensional Arrays (1D Arrays) — ◇Two-Dimensional Arrays (2D Arrays) Source / Reference:

◇References & Navigation

CONFIRMATION // 理解度の確認

ACTIVE RECALL VERIFICATION

Select an answer to verify conceptual comprehension and reveal the technical rationale.

Q1

Which of the following best describes an array in C?

Q2

Which syntax represents a valid 1D array declaration?

Q3

What is a key limitation of arrays in standard C?