0
0
Cprogramming~5 mins

Array traversal in C

Choose your learning style9 modes available
Introduction
Array traversal means looking at each item in an array one by one. It helps us use or check every element in the list.
When you want to print all items in a list.
When you want to find a specific value inside an array.
When you want to change or update every element in a list.
When you want to calculate something using all elements, like sum or average.
Syntax
C
#include <stdio.h>

int main() {
    int array_name[array_size] = {elements};
    int index;

    for (index = 0; index < array_size; index++) {
        // Access array_name[index] here
    }

    return 0;
}
The loop starts at index 0 because arrays in C start counting from zero.
The loop runs until index is less than the size of the array to avoid going outside the array.
Examples
This example prints all elements of the array 'numbers'.
C
#include <stdio.h>

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    int i;

    for (i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }

    return 0;
}
This example shows what happens if the array is empty. The loop does not run.
C
#include <stdio.h>

int main() {
    int i;

    for (i = 0; i < 0; i++) {
        // This loop will not run because array size is zero
    }

    printf("No elements to traverse.\n");
    return 0;
}
This example shows traversal of an array with only one element.
C
#include <stdio.h>

int main() {
    int single_element[1] = {99};
    int i;

    for (i = 0; i < 1; i++) {
        printf("%d\n", single_element[i]);
    }

    return 0;
}
Sample Program
This program prints the temperature for each day of the week by looking at each element in the 'temperatures' array.
C
#include <stdio.h>

int main() {
    int temperatures[7] = {23, 25, 22, 20, 24, 26, 21};
    int day_index;

    printf("Temperatures for the week:\n");
    for (day_index = 0; day_index < 7; day_index++) {
        printf("Day %d: %d degrees\n", day_index + 1, temperatures[day_index]);
    }

    return 0;
}
OutputSuccess
Important Notes
Time complexity is O(n) because we look at each element once.
Space complexity is O(1) because we only use a few extra variables.
A common mistake is going past the last index, which causes errors or crashes.
Use array traversal when you need to process or check every item in the list.
Summary
Array traversal means visiting each element in the array one by one.
Use a for loop starting at 0 and ending before the array size.
Always be careful not to go outside the array limits.