The short answer
To write a C program that uses an array, declare the array with a type and a size, fill it with values, loop over its elements, and print what you need. The steps are the same whether the array holds scores, temperatures or prices.
Readers new to arrays often ask “How do I define an array?” The answer is a type, a name and a size in square brackets. For example, int scores[5]; declares an array of five int values.
A complete example
The program below stores five test scores, adds them up, and prints the total and the average:
#include <stdio.h>
int main(void) {
int scores[] = {88, 92, 79, 95, 84};
int count = sizeof(scores) / sizeof(scores[0]);
int total = 0;
for (int i = 0; i < count; i++) {
total += scores[i];
}
printf("Total: %d\n", total);
printf("Average: %.2f\n", (double)total / count);
return 0;
}
The output is:
Total: 438
Average: 87.60
How the program works
- Declaration.
int scores[] = {88, 92, 79, 95, 84};makes an array of fiveintvalues. Because the list has five values, the compiler sets the size to five. Each element is anint, one of the primitive data types in c. - Counting the elements.
sizeof(scores)is the total size of the array in bytes. Dividing it bysizeof(scores[0]), the size of one element, gives the count, which is five. This works only where the array is declared. A function that receives the array needs the count passed in separately. - The loop. Indexes in C start at 0, so the loop runs from
i = 0up to, but not including,count. The linetotal += scores[i];adds each element to the total. - The average.
(double)total / countconvertstotalto adoublebefore dividing. Without the cast, dividing twointvalues gives 87 and drops the decimal part.
Compile and run
Save the code as scores.c, then compile it with GCC:
gcc -std=c11 -Wall -Wextra scores.c -o scores
./scores
On Linux or macOS, ./scores runs the program. The same file also compiles as C++ when saved as scores.cpp and built with:
g++ -Wall -Wextra scores.cpp -o scores
Common mistakes
- Going past the last index.
scores[5]is outside this array, because valid indexes run from 0 to 4. C doesn’t check array bounds, so the program may print a wrong value or crash. - Reading elements you haven’t set. A local array declared without values, such as
int values[5];, holds unknown values until you assign them. - Dividing two ints.
total / countgives 87 here, not 87.6. The cast in the example avoids this.
Next step: moving the loop into a function
Once the loop works, you might move it into a function so the same logic can be reused. A function that receives an array can’t measure it with sizeof, so you pass the array and its count. The syntax is covered in how to pass an array to a function in c.