Week 4 · Foundation

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

Create an array and store many values under a single name
Access each element through its index, starting from 0
Walk through the whole array with a loop and compute the sum and average
Understand that a string is actually a char array and the null terminator (\0)
Compute a string's length with strlen
Loop over the characters of a string one by one and change them

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:

ballar.c
1// instead of 5 separate variables
2int ballar[5] = {90, 85, 70, 88, 95};

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
Picture an array as a row of boxes in memory: equal cells standing side by side, each holding one value. This row is almost the same idea as a list in Scratch.

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:

Array visualizer click a cell
Click one of the cells above: you will see its index and value.
Because the index starts from 0, the last index is always equal to length minus one. In a 5-element array the last index is 4. If you write 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:

main.c
1int x = ballar[1]; // read: x is now 85
2ballar[1] = 100; // change: 100 instead of 85

Below, select an index, enter a new value and click the Set button. Only the selected cell changes:

Element changer select an index
ballar[
] =
amal.c
1ballar[0] = 100;
Select an index, enter a value and click the «Set» button.

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.

Code tracer (debugger) step through it
ballar.c
terminal

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?

main.c
1int a[4] = {2, 4, 6, 8};
2printf("%d", a[1] + a[3]);
10
12
6

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:

ism.c
1char ism[] = "Ali";
2printf("%s\n", ism); // %s for a string

Type a word and see which index each of its letters sits at:

String visualizer type a word
char so'z[] =

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:

Null terminator visualizer type a word
char ism[] =
That is why a word of n letters needs at least n plus 1 cells. If you size and create the array yourself, do not forget to leave room for \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:

strlen counter Compute
length: 0
Note: strlen counts only the real letters, it does not include \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:

Convert to uppercase Run
terminal

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:

Largest element finder step
eng_katta.c
1int max = ballar[0];
2for (int i = 1; i < 5; i++)
3 if (ballar[i] > max)
4 max = ballar[i];

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.

jadval.c
1int jadval[2][3] = {
2 {1, 2, 3}, // row 0
3 {4, 5, 6} // row 1
4};
5printf("%d\n", jadval[1][2]); // 6

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:

kunlar.c
1char *kunlar[] = {"Du", "Se", "Cho"};
2printf("%s\n", kunlar[0]); // Du
The * 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

arraya collection of values of the same type, under a single name.
indexan element's number, starting from 0.
elementa single cell in the array and the value in it.
stringa sequence of letters, actually a char array.
\0the null terminator, a special character marking the end of a string.
strlena function that computes a string's length (the number of letters).

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