Array indexing
Array Indexing An array is a collection of related data elements stored in contiguous memory locations. Each element in the array holds a single data typ...
Array Indexing An array is a collection of related data elements stored in contiguous memory locations. Each element in the array holds a single data typ...
An array is a collection of related data elements stored in contiguous memory locations. Each element in the array holds a single data type, and they share the same memory space. Arrays are declared using square brackets, with the data type followed by the variable name. For example:
c
int numbers[5] = {1, 3, 5, 7, 9};
Here, numbers is an array of 5 integers, each stored at a specific memory address.
Indexing allows us to access specific elements in the array by using an integer index. This is achieved using the syntax:
c
int value = numbers[index];
Examples:
numbers array:c
int first_element = numbers[0];
numbers array:c
int third_element = numbers[2];
numbers array:c
for (int i = 0; i < 5; i++) {
int element = numbers[i];
// do something with the element
}
Benefits of using arrays:
Efficiency: Arrays allow for efficient access to multiple elements, especially when dealing with large datasets.
Reusability: Arrays can be easily reused and assigned to other variables.
Data organization: Arrays help to organize and store related data.
Important notes:
Array indices are typically stored in memory, which means they are not accessible directly from the computer's registers.
The size of the array must be known at compile time.
Arrays can be used with different types of data