Accessing Elements of an Array in C programming

Accessing Elements of an Array in C

Accessing Elements of an Array in C

In C programming, arrays are used to store multiple values of the same type. To access these values, you use the array's name followed by the index of the element you want to access in square brackets ([]).

Syntax

The syntax for accessing an element of an array is:

array_name[index];

Example

Below is a simple example of how to declare an array and access its elements in C:

#include <stdio.h>

int main() {
    int arr[5] = {10, 20, 30, 40, 50}; // Declaring and initializing an array

    // Accessing and printing elements of the array
    printf("First element: %d\\n", arr[0]); // Accesses the first element (10)
    printf("Second element: %d\\n", arr[1]); // Accesses the second element (20)
    printf("Third element: %d\\n", arr[2]); // Accesses the third element (30)

    // Modifying an element of the array
    arr[3] = 100; // Sets the fourth element to 100
    printf("Modified fourth element: %d\\n", arr[3]); // Accesses the modified fourth element (100)

    return 0;
}

Explanation

  • arr[0] - Accesses the first element of the array, which is 10.
  • arr[1] - Accesses the second element of the array, which is 20.
  • arr[3] = 100; - Modifies the value of the fourth element from 40 to 100.
Note: Array indexing in C starts at 0, so the first element is accessed using index 0. Accessing an index outside the array's declared size will lead to undefined behavior.

Comments

Popular Posts