Accessing Elements
Part of the Fundamentals section of Coddy's C journey — lesson 54 of 63.
Arrays store multiple values of the same type. We use the index position to access individual elements in an array.
In C, array indices start at 0. This means the first element is at index 0, the second at index 1, and so on.
Create an integer array with 5 elements:
int numbers[5] = {10, 20, 30, 40, 50};Access the first element (index 0):
int firstElement = numbers[0];After executing the above code, firstElement contains:
10Access the third element (index 2):
int thirdElement = numbers[2];This stores the value 30 in thirdElement.
Trying to access an element outside the array bounds (like numbers[5] in our example) leads to undefined behavior and can cause program crashes.
Challenge
EasyWrite a function named getElement that:
- Takes an integer array and its size as parameters
- Takes an index parameter
- If the index is valid (within array bounds), it prints the element at that index
- If the index is invalid (outside array bounds), it prints “Index out of bounds”
Remember the index in arrays starts with 0, so if the 6th element is wanted you need to access array[5]
Cheat sheet
Arrays store multiple values of the same type. Array indices start at 0.
Create an integer array:
int numbers[5] = {10, 20, 30, 40, 50};Access elements using square brackets and index:
int firstElement = numbers[0]; // Gets 10
int thirdElement = numbers[2]; // Gets 30Accessing elements outside array bounds leads to undefined behavior and can cause crashes.
Try it yourself
#include <stdio.h>
void getElement(int arr[], int size, int index) {
// Write your code here
}
int main() {
int size, index;
// Read the size of the array
scanf("%d", &size);
int arr[size];
// Read array elements
for(int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Read the index to access
scanf("%d", &index);
getElement(arr, size, index);
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge