• Home
  • 5.3 Accessing Array Elements

5.3 Accessing Array Elements

View Categories

5.3 Accessing Array Elements

Individual array elements are accessed using the array name and an index enclosed in square brackets. C uses zero-based indexing, so the first element has index 0 and the last element of an array of size n has index n - 1.

#include <stdio.h>

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

    printf("First element: %d\n", numbers[0]);
    printf("Third element: %d\n", numbers[2]);
    printf("Last element: %d\n", numbers[4]);

    numbers[2] = 99;

    printf("Updated third element: %d\n", numbers[2]);

    return 0;
}

Example Output #

First element: 10
Third element: 30
Last element: 50
Updated third element: 99

Explanation #

The expression numbers[2] accesses the third element because indexing starts at zero.

numbers[2] = 99;

This statement replaces the existing value 30 with 99. Array elements can be read or modified individually when the array is writable.

Array Index Reference #

For the declaration:

int numbers[] = {10, 20, 30, 40, 50};
Index Expression Value
0 numbers[0] 10
1 numbers[1] 20
2 numbers[2] 30
3 numbers[3] 40
4 numbers[4] 50

An index can also be an integer variable or expression:

int index = 3;

printf("%d\n", numbers[index]);
printf("%d\n", numbers[index - 1]);

Output:

40
30

The index expression must identify an existing array element. For an array containing five elements, valid indices are 0 through 4. Accessing an element outside this range results in undefined behavior.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *