arrays

** Accessing Array Elements:**

Accessing array elements involves retrieving the value stored at a specific position in the array. Arrays are zero-indexed, which means the first element is at index 0, the second at index 1, and so on. To access an element, you use the array's name followed by square brackets containing the index of the element you want to access.

Modifying Array Elements:

Modifying array elements refers to changing the value stored at a particular position in the array. You can update an element by assigning a new value to its index using the assignment operator.

Now, let's provide examples in Python, C, and JavaScript to illustrate these concepts.

Examples:

Accessing Array Elements:

Suppose we have an array arr with the values [10, 20, 30, 40, 50].

  • To access the first element (10):

    • Index 0: arr[0]
  • To access the third element (30):

    • Index 2: arr[2]

Modifying Array Elements:

Using the same array arr as above:

  • To modify the second element to 25:

    • Index 1: arr[1] = 25
  • To modify the fourth element to 45:

    • Index 3: arr[3] = 45

These concepts apply generally to array manipulation in most programming languages.

Now, let's see the examples in our supported programming languages.

Python:

1 2my_list = [10, 20, 30, 40, 50] 3 4 5# Accessing array elements 6 7first_element = my_list[0] # Accesses the first element (10) 8 9third_element = my_list[2] # Accesses the third element (30) 10 11 12# Modifying array elements 13 14my_list[1] = 25 # Modifies the second element to 25 15 16my_list[3] = 45 # Modifies the fourth element to 45 17

C:

1 2int my_array[5] = {10, 20, 30, 40, 50}; 3 4 5// Accessing array elements 6 7int first_element = my_array[0]; // Accesses the first element (10) 8 9int third_element = my_array[2]; // Accesses the third element (30) 10 11 12// Modifying array elements 13 14my_array[1] = 25; // Modifies the second element to 25 15 16my_array[3] = 45; // Modifies the fourth element to 45 17

JavaScript:

1 2let myArray = [10, 20, 30, 40, 50]; 3 4 5// Accessing array elements 6 7let firstElement = myArray[0]; // Accesses the first element (10) 8 9let thirdElement = myArray[2]; // Accesses the third element (30) 10 11 12// Modifying array elements 13 14myArray[1] = 25; // Modifies the second element to 25 15 16myArray[3] = 45; // Modifies the fourth element to 45 17