Array access
- C course
- Beginner
- Lesson 54/116
- 4 min
Learn to access and modify array elements by index.
Array access
You access array elements by index. Index starts at 0; for an array of length n the last index is n - 1.
int scores[5] = {85, 92, 78, 90, 88};
printf("%d\n", scores[0]); // 85
printf("%d\n", scores[4]); // 88
scores[2] = 80; // change 78 to 80If the index is out of bounds the behavior is undefined; that's why loops use i < n, not i <= n. You can both read and write an element.
Modifying elements
You can change an array element with =. The old value is lost, the new value is written to that index.
int nums[3] = {10, 20, 30};
nums[1] = 99;
printf("%d %d %d\n", nums[0], nums[1], nums[2]);
// Output: 10 99 30Here nums[1] was 20; we set it to 99. The other elements stay unchanged. This is useful for updating elements based on conditions inside loops.
Practice Modify an element and print
Write a C program. Declare int nums[3] = {10, 20, 30};. Change the middle element with nums[1] = 99;. Print the three values with printf("%d %d %d\n", nums[0], nums[1], nums[2]);. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare nums, change the middle element to 99 and print
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int nums[3] = {10, 20, 30};
nums[1] = 99;
printf("%d %d %d\n", nums[0], nums[1], nums[2]);
return 0;
}Expected output
10 99 30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Access the first element
printf("%d
", scores[____]);
printf("%d
", scores[0]);
Explanation: scores[0] is the first element.
2 What's the last index of scores[5]?
int scores[5] = {1,2,3,4,5};- 0
- 5
- 4 Correct answer
- 6
Explanation: A 5-element array's last index is 4.
3 Match the index concepts
| Term | Meaning |
|---|---|
scores[0] |
First element |
scores[4] |
Last element (size 5) |
nums[1] = 99 |
Modification |
scores[5] |
Out of bounds |