Summary
In this lesson, you learned that:
- An array stores several values of the same type, its elements, under one name:
int scores[5] = {80, 92, 75, 60, 88};. Withint scores[] = {80, 92, 75};, the compiler counts the elements itself. The size of an array is fixed and can't change. - Each element has an index, counted from 0, so the last index is the size − 1.
scores[0]reads the first element,scores[2] = 79;changes the third one. An element behaves like a variable of its type, soscores[1] += 5;works too. - An index can be a variable, so a
forloop can go through all the elements:for (int i = 0; i < count; i++), with<, not<=. You can't print a whole array withprintf: print it element by element, in a loop. - An index outside the array is a mistake. When it's a number in the code, the program doesn't compile (
array index 5 is past the end of the array). When it's a variable, the program stops withRuntimeError: unreachable. C itself doesn't check indexes. - The number of elements can be kept in a constant,
const int COUNT = 5;, or calculated from the array:int count = sizeof(scores) / sizeof(scores[0]);. Withsizeof, the loops stay right when the array changes. - Patterns with arrays: the sum (a variable that starts at 0 before the loop,
+=in the loop, the result printed after the loop), the average ((double)total / count), counting (a counter with++inside anif) and the largest value (start with the first element, not with 0, and keep the index too if you need to know where it is). int squares[10];creates an array without values, which a loop can fill.int votes[4] = {0};sets all the elements to zero. An array can't be assigned or copied with=: copy it element by element.- A two-dimensional array has rows and columns:
int seats[3][4].seats[1][2]is the element in the row with index 1 and the column with index 2. Two nested loops go through all the elements.
In the next lesson, on strings, you'll find out that text in C is an array too: an array of characters. But first, practice what you know on the temperatures of one week.
Instructions
The array temperatures holds the temperatures of one week. Calculate the average temperature and print it with one decimal place: Average: 18.3. Get the number of days with sizeof.
Find the warmest day. Print its number, counted from 1, and its temperature: Warmest: day 5, 23 degrees.
Start programming for free
12/12