Arrays and strings
Last week one variable stored one value. Now we learn to store several values under a single name, that is, arrays. Then we look at strings: in C a string is actually an array of characters. We go through each idea step by step in a live array visualizer and an IDE-style code tracer.
What you will learn in this lesson
4.1 What is an array?
Imagine you need to store the grades of 5 students in a class. With last week's knowledge you would have written five separate variables: ball1, ball2, ball3 and so on. For 5 that is bearable, but what if there are 30 or 100 students?
This exact problem is solved by an array. An array means storing several values of the same type under a single name. The five grades now sit side by side under one ballar name:
Five grades were stored in a single line. They are all in one place, in order, and we can easily loop over them. An array has two main properties:
- All elements are of the same type, for example all
int - The number of elements is fixed in advance and does not change afterwards, here 5
4.2 Creating it and the index
When we create an array we write how many elements there are inside the square brackets, and the values inside the curly braces. Now the most important idea: each element has its own index (number), and counting starts not from 1, but from 0.
So in a 5-element array the indexes are 0, 1, 2, 3, 4. The first element is ballar[0] and the last is ballar[4]. Try clicking a cell below:
ballar[5], you go past the array boundary, which is a serious error.4.3 Reading and changing
Using the index we can read or change each cell separately. To read we simply write the index, and to change we give it a new value:
Below, select an index, enter a new value and click the Set button. Only the selected cell changes:
4.4 Looping over an array
An array's real power is unlocked together with a loop. Instead of writing each element by hand, with a for loop we move the index from 0 to the end and access each cell in turn. The program below adds up all the grades and prints the sum.
Step through it: the yellow line shows the current line, and the green cell shows the element being read at that step.
The sum came out as 428. To find the average we divide it by the number of elements: 428 / 5. With the same pattern we can also count the largest, the smallest or how many passed.
Make a prediction
What does this program print to the terminal?
4.5 Strings (string)
Now let us move on to letters. Last week we saw that the char type stores a single letter. But a word, a name or a sentence is made up of many letters. To store these we use a string.
The most important idea is this: in C a string is actually an array of chars. That is, a string is just like an array, except it holds letters inside rather than numbers. Each letter has its own index, and counting again starts from 0:
Type a word and see which index each of its letters sits at:
4.6 Null terminator (\0)
Here there is a subtle but very important rule in C. How does the computer know where a string ends in memory? For this, C puts an invisible special character at the end of every string: the null terminator, that is \0. It means "the string ends here".
So even though "Ali" is three letters, it occupies four cells in memory: A, l, i and \0 at the end. Type a word below and pay attention to the \0 cell at the end:
\0. If you write "Ali" in quotes, C does this automatically.4.7 strlen: string length
Often we need to know how many letters a string consists of. We do not sit and count this by hand, there is a ready-made function: strlen (string length). It walks from the start of the string, counts the letters and stops when it reaches \0.
This function lives in the string.h library, so at the start of the program you need to write #include <string.h>. Type a word below and click the Compute button, watch how strlen counts:
\0. That is why the result of strlen("Ali") is 3, even though there are 4 cells in memory.4.8 Looping over characters
Because a string is an array, we can loop over it too. But here there is an elegant approach: we do not need to know the length in advance, we simply walk until we reach \0. The loop condition checks exactly this: ism[i] != '\0'.
For example, we turn each lowercase letter into an uppercase one. In the ASCII table lowercase 'a' is 97 and uppercase 'A' is 65, that is, the difference between them is 32. So if we subtract 32 from a lowercase letter, we get the uppercase one. Click the Run button:
4.9 Practical: finding the largest element
This is one of the most frequent tasks with arrays, and it serves as a bridge to the algorithms we learn next week. The idea is simple: we temporarily take the first element as the "largest", then look at the rest one by one, and whenever we find a larger one, we update the "largest".
Below, the green cell stands for the current largest, and the blue cell for the element being checked. Walk through it with the Next step button:
4.10 Going deeper advanced
You have mastered the basics of arrays and strings. Now let us briefly look at two more extensions: there is no need to study these fully right now, just having a general idea is enough.
Two-dimensional array (matrix)
We pictured an array as a row. If the cells are arranged not only along a row but also along columns, a two-dimensional array is formed: this is a table or a matrix. For example, a chessboard or an Excel sheet is like this.
Now an element is taken with two indexes: jadval[row][column]. Above, jadval[1][2] gives the value at row 1, column 2, that is 6.
Array of strings
Just as a string is a char array, several strings can also be gathered into one array. This is convenient, for example, for storing a list of the days of the week or of names:
* symbol above means a pointer. It works with an address in memory, and we will study it separately and in depth in the coming weeks. For now it is enough to understand it as "each cell holds one string".Glossary of terms
4.11 Knowledge quiz
16 questions. To complete the week, answer at least 11 of them correctly.
Congratulations! Week 4 is complete
Now you can work with arrays and strings: storing many values, accessing by index, looping, the null terminator and strlen. These are the foundation of almost every program that works with data.
Next week: Algorithms (linear and binary search, sorting, Big-O efficiency).
Go to the next module