Back to course

Iterating Over Arrays and Array Operations

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 28: Iterating Over Arrays and Array Operations

Since array elements are accessed sequentially via indices, loops (especially for loops) are the standard way to process arrays.

Iterating and Printing Array Contents

c #include <stdio.h>

int main() { int data[] = {45, 67, 12, 89, 33}; int size = sizeof(data) / sizeof(data[0]); // Calculate size dynamically

printf("Array elements:\n");
for (int i = 0; i < size; i++) {
    printf("Element at index %d: %d\n", i, data[i]);
}
return 0;

}

Common Array Operation: Summation

c #define ARRAY_SIZE 5

int main() { int values[ARRAY_SIZE] = {10, 20, 30, 40, 50}; int sum = 0;

for (int i = 0; i < ARRAY_SIZE; i++) {
    sum += values[i]; // sum = sum + values[i]
}

printf("Total sum: %d\n", sum); // Output: 150
return 0;

}

Boundary Checking

C does not automatically perform array boundary checking at runtime. Accessing an element outside the defined size (e.g., data[10] when size is 5) is called Array Bounds Violation. This can lead to reading or writing to arbitrary memory locations, causing crashes, data corruption, or security vulnerabilities.