An array stores an ordered group of values of the same type. Every element is accessed by index, and the array length is fixed when it is created.
Creating arrays
Use an array initializer when the values are known. int counts[4] = {0} creates four zero-initialized slots. The element type comes before the variable name, and brackets mean “a group of this type.”
int scores[] = {88, 91, 76, 95, 83};
int counts[4] = {0};
counts[0] = 12;
counts[1] = 9;Initializing an int array with {0} sets every element to 0; an uninitialized local array does not receive automatic default values. The slot count is decided when the array is created.
KNOWLEDGE QUIZ
Accessing array elements
Array indexes start at 0, so the first element is scores[0]. An array of length 5 has indexes 0 through 4. Accessing scores[5] does not throw automatically; it causes undefined behavior.
int scores[] = {88, 91, 76, 95, 83};
printf("%d\n", scores[0]); // 88
printf("%d\n", scores[4]); // 83
scores[2] = 80;
printf("%d\n", scores[2]); // 80Array index spotlight
Select any slot and let a C expression point to exactly one value. Valid indexes always run from 0 through score_count-1.
KNOWLEDGE QUIZ
Array length and loops
Built-in arrays have no length field. This array has five elements, so the example directly uses score_count = 5; the last valid index is score_count - 1.
int score_count = 5;
for (int i = 0; i < score_count; i++) {
printf("scores[%d] = %d\n", i, scores[i]);
}
for (int i = 0; i < score_count; i++) {
printf("%d\n", scores[i]);
}KNOWLEDGE QUIZ
Fixed length and common operations
You can read or rewrite existing elements and use a loop to find a value. None of these actions adds or removes slots.
int values[] = {4, 0, 7, 0, 2, 9};
int count = 6;
values[2] = 5;
for (int i = 0; i < count; i++) {
if (values[i] == 0) {
printf("Found 0 at index %d\n", i);
}
}KNOWLEDGE QUIZ
Move zeroes to the end of an array
Given {0, 1, 0, 3, 12}, move every zero to the end in place while preserving the order of nonzero elements.
- Scan every element with a read index.
- Use a write index for the next nonzero destination.
- Fill the remaining cells with zero after the scan.
Reverse an integer array in place
Use two indexes, left and right, moving inward while swapping values. Transform {2, 4, 6, 8, 10} into {10, 8, 6, 4, 2}.
- Point left at the first element and right at the last.
- Swap both ends, then move both indexes inward.
- Stop when left is no longer less than right and print the array.