Step 1 of 7
Declare and index
Suppose a game tracks the score of 5 players. Five separate variables (score1, score2, ...) work, but they're painful: you can't loop over them, and 100 players would need 100 names. An array solves this: one name for a whole row of values of the same type, stored side by side in memory.
#include <stdio.h>
int main(void) {
int temps[4] = {18, 21, 25, 19};
printf("first: %d\n", temps[0]);
printf("third: %d\n", temps[2]);
temps[3] = 20;
printf("last is now: %d\n", temps[3]);
return 0;
}
first: 18
third: 25
last is now: 20
Declaring
int temps[4] creates 4 ints in a row. The size must be known when the array is created and it never changes. The { ... } list gives initial values. If the list is shorter than the size, the rest are set to 0, so int counts[10] = {0}; is a handy way to zero a whole array. You can also leave the size out and let the list decide: int temps[] = {18, 21, 25, 19}; has size 4.
Indexing starts at 0
temps[i] is element number i, counting from 0. An array of size 4 has indexes 0, 1, 2, 3, so the last one is always size - 1. The index is really an offset: how many elements past the start. The first element is 0 steps from the start.
No safety net
C does not check indexes. temps[4] or temps[-1] compiles fine and reads or writes whatever memory happens to be next to the array. That's undefined behavior: the program might crash, print garbage, or seem to work and fail later. Keeping indexes in range is your job.
Your turn: print the first and the last element of the array.