Arrays
An array holds a fixed number of values of the same type, side by side in memory.
C
#include <stdio.h>
int main() {
int scores[5] = {72, 95, 88, 61, 79};
printf("First: %d\n", scores[0]);
printf("Last: %d\n", scores[4]);
scores[3] = 65; // change an element
for (int i = 0; i < 5; i++) {
printf("scores[%d] = %d\n", i, scores[i]);
}
return 0;
}Indexes start at 0, so an array of 5 has indexes 0 to 4.
Total, average and maximum
C
#include <stdio.h>
int main() {
int values[6] = {4, 8, 15, 16, 23, 42};
int n = 6, total = 0, max = values[0];
for (int i = 0; i < n; i++) {
total += values[i];
if (values[i] > max) max = values[i];
}
printf("Total %d, average %.2f, max %d\n", total, (double)total / n, max);
return 0;
}Passing arrays to functions
A function can't tell how long an array is, so pass the length too:
C
#include <stdio.h>
int sum(int arr[], int length) {
int s = 0;
for (int i = 0; i < length; i++) s += arr[i];
return s;
}
int main() {
int a[4] = {1, 2, 3, 4};
int b[3] = {10, 20, 30};
printf("%d %d\n", sum(a, 4), sum(b, 3));
return 0;
}Unlike ordinary variables, an array passed to a function is not copied: the function works on the original.
Two-dimensional arrays
C
#include <stdio.h>
int main() {
int grid[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
printf("%3d", grid[r][c]);
}
printf("\n");
}
printf("Centre: %d\n", grid[1][1]);
return 0;
}Finished this lesson?Mark it complete to earn +20 XP and move your progress on.