#include <stdio.h>
// Function to access element at given index
int access_element(int arr[], int size, int index) {
if (index < 0 || index >= size) {
return -1; // index out of bounds
}
return arr[index]; // direct access by index
}
int main() {
int arr[] = {5, 8, 2, 9};
int size = sizeof(arr) / sizeof(arr[0]);
int index = 2;
int value = access_element(arr, size, index);
if (value == -1) {
printf("Index out of bounds\n");
} else {
printf("Array: [5, 8, 2, 9]\n");
printf("Accessed value at index %d: %d\n", index, value);
}
return 0;
}
if (index < 0 || index >= size) {
check if index is valid to avoid errors
directly access the element at given index for fast retrieval
Array: [5, 8, 2, 9]
Accessed value at index 2: 2