C Arrays
An array stores many values of the same type under one name, such as the marks of a class. Each value is an element, and you reach it by its position, the index.
Creating an array
Write the type, the name and the number of elements in square brackets. The values can be given in curly braces.
#include <stdio.h>
int main(void) {
int marks[5] = {78, 85, 62, 90, 74};
printf("First mark: %d\n", marks[0]);
printf("Third mark: %d\n", marks[2]);
marks[2] = 65; // change an element
printf("Third mark now: %d\n", marks[2]);
return 0;
}First mark: 78 Third mark: 62 Third mark now: 65
Indexes start at 0, so an array of 5 elements has the indexes 0 to 4. marks[5] does not exist.
Looping over an array
A for loop from 0 while the index is less than the size visits every element once:
#include <stdio.h>
int main(void) {
int marks[5] = {78, 85, 62, 90, 74};
int total = 0, highest = marks[0];
for (int i = 0; i < 5; i++) {
total += marks[i];
if (marks[i] > highest) {
highest = marks[i];
}
}
printf("Total: %d\n", total);
printf("Average: %.2f\n", total / 5.0);
printf("Highest: %d\n", highest);
return 0;
}Total: 389 Average: 77.80 Highest: 90
The size of an array
sizeof(marks) is the size of the whole array in bytes, and sizeof(marks[0]) the size of one element. Dividing them gives the number of elements, so the loop keeps working if you add values:
#include <stdio.h>
int main(void) {
int primes[] = {2, 3, 5, 7, 11, 13};
int count = sizeof(primes) / sizeof(primes[0]);
printf("%d primes:", count);
for (int i = 0; i < count; i++) {
printf(" %d", primes[i]);
}
printf("\n");
return 0;
}6 primes: 2 3 5 7 11 13
When you give all the values, you may leave the size out (int primes[] = {...}); the compiler counts them. Elements you do not give a value are set to 0: int zeros[10] = {0}; makes ten zeros.
Index outside the array
C does not check indexes. Writing marks[5] or marks[-1] reads or changes memory that belongs to something else, and the program may misbehave much later, far from the mistake. Always keep the index between 0 and size minus 1. In the editor, Safe mode stops the program at such an index and names the function.
Practice exercises
- Read 5 numbers into an array and print them in reverse order.
- Count how many elements of an array are above the average.
- Find the smallest value and its position in one loop.
- Copy one array into another with a loop (arrays cannot be copied with
=).