Storing Records with Parallel Arrays: Names, Ages, and Marks

In Strings in C: char Arrays, %s, fgets, and strlen you stored a name in a char array, and in the arrays lesson before it you stored five scores in an int array. A real class list needs both, and more: for every student, a name, an age and an average mark. In this lesson you keep a small class list in three arrays that work together, print it as a neat table, type the records in, look one up, find the top mark, and then scramble the records on purpose.

In this lesson you will

  • Describe a student as a record made of fields: name, age and average mark
  • Store the records in parallel arrays, where the same index in every array is one record
  • Print a lined-up table with printf widths such as %-10s, %3d and %6.1f
  • Enter records with fgets and scanf, and deal with the leftover Enter
  • Look up one record by its number, and find the record with the highest mark
  • Break it on purpose: mismatch an index, and reorder one array but not the others

Start a new project for this lesson. Copy 005-StringsCProgram to a new folder named 006-RecordsCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.

Records and fields

The thing we keep data about, here a student, is called an entity. All the data about one student is a record, and each item in the record is a field. Our records have three fields: a name (text), an age (a whole number) and an average mark (a decimal number). Because the fields have different types, they cannot share one array. Instead we use one array per field:

    char names[5][20];   /* 5 names, each up to 19 characters */
    int ages[5];
    float marks[5];

char names[5][20] is an array of 5 strings, and each string is itself a char array of 20. Read it as “5 rows of 20 characters”. names[0] is the first name, and you use it anywhere you used name in the strings lesson. The key idea is that the three arrays are parallel: the same index in each array belongs to the same student. Record 2 is names[2], ages[2] and marks[2], together:

Record (index i)Name: names[i]Age: ages[i]Average mark: marks[i]
0"Ken"1672.5
1"Aaliyah"1788.0
2"Ravi"1664.5
3"Shania"1891.5
4"Marcus"1779.0

Each row is one record. Each column is one field, stored in its own array. Nothing in C ties the three arrays together: the only link between "Ravi", 16 and 64.5 is that they all sit at index 2. Keep that in mind for the break-it sections.

Try it: print the class list

Start with the data typed into the program, using initialiser lists. An array of strings takes a list of string literals:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
    int i;

    printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
    for (i = 0; i < 5; i++)
    {
        printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i], marks[i]);
    }
    return 0;
}
No  Name       Age   Mark
0   Ken         16   72.5
1   Aaliyah     17   88.0
2   Ravi        16   64.5
3   Shania      18   91.5
4   Marcus      17   79.0

The loop is the same for (i = 0; i < 5; i++) pattern from the arrays lesson. On each pass, one printf prints field after field of record i, so one pass is one row of the table.

What just happened: printf widths

A number between the % and the letter is a width: the least number of characters the value takes up. Shorter values are padded with spaces, which is what lines the columns up:

  • %-10s: a string in 10 characters. The - means left-aligned, padded on the right. Ken becomes Ken plus 7 spaces.
  • %3d: an int in 3 characters, right-aligned (no -), so 16 becomes a space and 16.
  • %6.1f: a float in 6 characters with 1 decimal place. You already know .1 from %.2f; the 6 is the width.
  • %-3d: the record number, left-aligned in 3 characters.

The heading line uses the same widths with %s for every column, so the titles sit above their columns. Try changing %-10s to %10s in both lines and run again: the names line up on the right instead. Change it back. A value longer than its width is never cut off; it just pushes the rest of the line along.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
    int i;

    printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
    for (i = 0; i < 5; i++)
    {
        printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i + 1], marks[i]);
    }
    return 0;
}

Break it on purpose: mix up the index

In the loop, change ages[i] to ages[i + 1] and leave the other two as they are. The program is shown above. Build and run. There is no error. On our test computer it printed:

No  Name       Age   Mark
0   Ken         17   72.5
1   Aaliyah     16   88.0
2   Ravi        18   64.5
3   Shania      17   91.5
4   Marcus       0   79.0

Every age is now from the next student: Ken has Aaliyah’s age, Aaliyah has Ravi’s, and so on. Each row looks perfectly sensible, which is what makes this mistake dangerous: the compiler cannot know which age belongs to whom. The last row is worse. For i = 4 it reads ages[5], which is out of bounds, so the 0 is just whatever was in memory there (undefined behaviour, as in the arrays lesson); yours may differ. The rule for parallel arrays: one record, one index, the same in every array. Change it back to ages[i].

Try it: type the records in

Now let the user enter each student. Names can contain a space (Ken Ali), so read them with fgets and remove the Enter, as in the strings lesson. names[i] is a char array, so it needs no &; ages[i] and marks[i] are single numbers, so they do. Here is a first try:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char names[5][20] = {""};
    int ages[5] = {0};
    float marks[5] = {0};
    int i;

    for (i = 0; i < 5; i++)
    {
        printf("Record %d name: ", i);
        fgets(names[i], sizeof(names[i]), stdin);
        names[i][strcspn(names[i], "\n")] = '\0';   /* remove the Enter */
        printf("Age: ");
        scanf("%d", &ages[i]);
        printf("Average mark: ");
        scanf("%f", &marks[i]);
    }

    printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
    for (i = 0; i < 5; i++)
    {
        printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i], marks[i]);
    }
    return 0;
}

Break it on purpose: forget the leftover Enter

Build and run. Type Ken Ali, 16 and 72.5, pressing Enter after each. Observe: the program never waits for the second name. It jumps straight to Age::

Record 0 name: Ken Ali
Age: 16
Average mark: 72.5
Record 1 name: Age: 

Keep typing the same answers in the same order (Aaliyah Mohammed, 17, 88, and so on) wherever the program stops. On our test computer, the table at the end came out like this:

No  Name       Age   Mark
0   Ken Ali     16   72.5
1                0    0.0
2   Aaliyah Mohammed  17   88.0
3                0    0.0
4   Ravi Singh  16   64.5

Records 1 and 3 are empty and everyone else has shifted down. This is the input buffer again. scanf("%f") read 72.5 and stopped, leaving your Enter waiting. The next fgets read that Enter as a complete, empty line, so record 1 got an empty name. Then scanf("%d") met the letters of Aaliyah, could not read them as a number, and left them (and ages[1], still 0) alone, so the next fgets picked up the name one record late. One leftover Enter threw every record after it out of line.

The fix is to take that one leftover Enter out of the buffer before the next fgets. getchar(), from stdio.h, reads exactly one character. Add it straight after the scanf for the mark:

        scanf("%f", &marks[i]);
        getchar();   /* eat the Enter left after the mark */

Build and run again, and enter all five students:

Record 0 name: Ken Ali
Age: 16
Average mark: 72.5
Record 1 name: Aaliyah Mohammed
Age: 17
Average mark: 88
Record 2 name: Ravi Singh
Age: 16
Average mark: 64.5
Record 3 name: Shania Joseph
Age: 18
Average mark: 91.5
Record 4 name: Marcus Lee
Age: 17
Average mark: 79
No  Name       Age   Mark
0   Ken Ali     16   72.5
1   Aaliyah Mohammed  17   88.0
2   Ravi Singh  16   64.5
3   Shania Joseph  18   91.5
4   Marcus Lee  17   79.0

Every record is right. Notice rows 1 and 3: Aaliyah Mohammed and Shania Joseph are longer than 10 characters, so, as promised, %-10s does not cut them off and the rest of the row is pushed along. Widen the name column to %-18s in both printf lines and the table lines up again. Remember too that each name holds at most 19 characters; fgets stops there, safely.

Try it: look up one record

Because a record is just an index, finding a student by number is one scanf. Go back to the typed-in data and replace main with this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};

    int n = 0;

    printf("Which record (0 to 4)? ");
    scanf("%d", &n);

    printf("Name: %s\n", names[n]);
    printf("Age: %d\n", ages[n]);
    printf("Average mark: %.1f\n", marks[n]);
    return 0;
}

Run it and type 3:

Which record (0 to 4)? 3
Name: Shania
Age: 18
Average mark: 91.5

The single number n picks out all three fields of record 3. Now run it again and type 7. There are only 5 records, so names[7], ages[7] and marks[7] are all out of bounds: you may get garbage, an empty name, or a crash. The program cannot refuse a bad number yet, because that needs an if, which you meet properly in a later lesson.

Try it: who has the top mark?

To find the best student, look at every mark and remember the index of the highest so far. This needs one new idea, the if statement, shown here only lightly: if (condition) { ... } runs the statements in the braces only when the condition is true. You will learn it properly later.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
    int i;

    int best = 0;   /* index of the best record so far */

    for (i = 1; i < 5; i++)
    {
        if (marks[i] > marks[best])
        {
            best = i;
        }
    }

    printf("Top mark: %s, age %d, with %.1f\n", names[best], ages[best], marks[best]);
    return 0;
}
Top mark: Shania, age 18, with 91.5

best starts at 0, assuming the first student is the best so far, so the loop starts from index 1. On each pass, marks[i] > marks[best] asks “is this mark higher than the best so far?” If it is, best becomes i. Trace it: 88.0 beats 72.5 (best = 1), 64.5 does not, 91.5 beats 88.0 (best = 3), 79.0 does not. Because best is an index, not a mark, it finds the whole record: the name and age come along for free. Try it: change > to < and the program finds the lowest mark instead. What does it print?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
    int ages[5] = {16, 17, 16, 18, 17};
    float marks[5] = {91.5, 88.0, 79.0, 72.5, 64.5};
    int i;

    printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
    for (i = 0; i < 5; i++)
    {
        printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i], marks[i]);
    }
    return 0;
}

Break it on purpose: sort one array and not the others

A teacher wants the list from highest mark to lowest. A thought experiment: what if you sort only marks? Go back to the table program and change just the marks list to {91.5, 88.0, 79.0, 72.5, 64.5}, the same five marks in order, leaving names and ages alone. The program is shown above. Build and run:

No  Name       Age   Mark
0   Ken         16   91.5
1   Aaliyah     17   88.0
2   Ravi        16   79.0
3   Shania      18   72.5
4   Marcus      17   64.5

The marks are sorted, but now Ken has Shania’s 91.5 and Shania has Ken’s 72.5. Every mark still exists, but most are attached to the wrong student. With parallel arrays, any reordering must move all the fields of a record together: whenever you move marks[i], you must move names[i] and ages[i] in exactly the same way. Forget one array once, and the records are scrambled for good.

That is the weakness of parallel arrays: the fields of one record are spread across separate arrays, held together only by your care with the index. C has a better tool, the struct, which groups a record’s fields into one variable, so a student’s name, age and mark travel together. Structs are coming in a later lesson.

Common mistakes

  • Using different indexes for the same record, such as names[i] with ages[i + 1].
  • Reordering, adding or deleting in one array but not the others.
  • Forgetting getchar() after scanf, so the next fgets reads an empty line.
  • Putting & in front of names[i] (a string), or leaving it off &ages[i] (a number).
  • Looking up a record number outside 0 to 4.

Key terms

  • Entity: the thing you store data about, here a student.
  • Record: all the data about one entity, such as one student’s name, age and mark.
  • Field: one item in a record, such as the age.
  • Parallel arrays: separate arrays, one per field, where the same index in each array is one record.
  • Array of strings: a two-dimensional char array such as char names[5][20]: 5 strings of up to 19 characters.
  • Field width: the number in a format specifier, such as the 10 in %-10s, giving the least number of characters to print. - means left-aligned.
  • getchar(): reads one character from the input; used here to remove a leftover Enter.
  • if: runs a block of statements only when a condition is true (a full lesson comes later).
  • struct: a C type that groups the fields of a record together (coming in a later lesson).

Quick check

  1. In the class list, which three elements make up record 4?

    Show answer

    names[4], ages[4] and marks[4]: Marcus, 17, 79.0.

  2. What does printf("[%-6s][%4d]", "Ana", 15); print?

    Show answer

    [Ana ][ 15]: Ana left-aligned in 6 characters, 15 right-aligned in 4.

  3. A program reads a mark with scanf("%f", &marks[i]); and then the next name with fgets, but every name after the first is empty. Why, and what is the fix?

    Show answer

    scanf leaves the Enter in the input buffer, and fgets reads it as an empty line. Add getchar(); after the scanf.

  4. Why does the top-mark program remember best as an index rather than the mark itself?

    Show answer

    An index identifies the whole record, so names[best] and ages[best] give the name and age that go with the mark.

  5. You sort names into alphabetical order but leave ages and marks alone. What goes wrong?

    Show answer

    The records are scrambled: names no longer line up with their ages and marks, because each record is held together only by its index.

Part of the Introduction to C series. Next: Storing Data in Files (Plain Text and Binary)

Arrays in C: Storing Many Values Under One Name

Every variable so far has held exactly one value. In Using Library Functions: #include, getch(), and the Input Buffer you used functions that other people wrote; in this lesson you learn to keep a whole list of values under one name. You start with five test scores in five separate variables, feel how quickly that gets painful, then store them in one array, visit every score with a short loop, work out the average, and break it on purpose by reaching past the end.

In this lesson you will

  • See why five separate variables (score1 to score5) do not scale
  • Declare an array, give it a size, and read and write its elements by index, counting from 0
  • Fill an array in one line with an initialiser list { }
  • Meet a first for loop, just enough to visit every index, and use it to print, total and average the scores
  • Read values into the array with scanf
  • Break it on purpose: go past the end, forget the size, copy with =, and use <= in the loop

Start a new project for this lesson. Copy 003-FunctionDemoCProgram to a new folder named 004-ArraysCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.

Try it: five scores, five variables

Suppose a teacher wants the total of five test scores. With what you know so far, you need one variable per score:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int score1 = 72;
    int score2 = 85;
    int score3 = 64;
    int score4 = 90;
    int score5 = 58;

    int total = score1 + score2 + score3 + score4 + score5;
    printf("Total: %d\n", total);
    return 0;
}
Total: 369

It works, but imagine the class has 30 students. That is 30 declarations, and a sum line with 30 names in it. Miss one and the total is wrong with no error. Every new score means editing the program in several places. What we want is one name for the whole list of scores, and a number that says which score we mean.

Try it: one array, five boxes

Replace main with this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5];

    scores[0] = 72;
    scores[1] = 85;
    scores[2] = 64;
    scores[3] = 90;
    scores[4] = 58;

    printf("First score: %d\n", scores[0]);
    printf("Last score: %d\n", scores[4]);

    scores[2] = 70;
    printf("Third score, corrected: %d\n", scores[2]);
    return 0;
}
First score: 72
Last score: 58
Third score, corrected: 70

What just happened

int scores[5]; declares an array of 5 int variables side by side in memory, all called scores. The number in square brackets in the declaration is the size: how many elements (boxes) the array has. After that, a number in square brackets is an index: which box you mean. scores[0] = 72; writes to a box, and scores[0] inside printf reads from it. Each element behaves exactly like an ordinary int variable.

Counting starts at 0. An array of size 5 has indexes 0, 1, 2, 3 and 4. There is no scores[5]. In memory it looks like this:

Elementscores[0]scores[1]scores[2]scores[3]scores[4]
Index01234
Contents7285709058
Which score1st2nd3rd4th5th

Notice that the 1st score is at index 0 and the 5th is at index 4: the index is always one less than the position. Changing scores[2] to 70 changed one box and left the others alone.

Try it: fill it in one line

Writing each element on its own line is still long. You can fill an array as you declare it with an initialiser list: the values in curly braces, separated by commas, in index order:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};

    printf("Second score: %d\n", scores[1]);
    printf("Fourth score: %d\n", scores[3]);
    return 0;
}
Second score: 85
Fourth score: 90

The first value goes into scores[0], the next into scores[1], and so on. If you give fewer values than the size, the rest are set to 0, so int scores[5] = {0}; is a handy way to start with every box at 0, just like the defensive initialisation in the scanf lesson.

Now break the declaration:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[];

    printf("Second score: %d\n", scores[1]);
    printf("Fourth score: %d\n", scores[3]);
    return 0;
}

Break it on purpose: forget the size

Change the declaration to int scores[];, with no size and no initialiser list. Build it. The build stops with:

main.c:6:9: error: array size missing in 'scores'

C must know how many boxes to set aside before the program runs. Either put the size in the brackets, or give an initialiser list so the compiler can count the values: int scores[] = {72, 85, 64, 90, 58}; makes an array of 5. Put the 5 and the list back.

Try it: visit every index with a for loop

Printing each score with its own printf is no better than five variables. The point of an index is that it can be a variable: scores[i] means “the box whose number is in i”. A for loop lets i take the values 0, 1, 2, 3, 4 in turn. Loops get a lesson of their own later. For now, learn this one pattern:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};
    int i;

    for (i = 0; i < 5; i++)
    {
        printf("scores[%d] = %d\n", i, scores[i]);
    }
    return 0;
}
scores[0] = 72
scores[1] = 85
scores[2] = 64
scores[3] = 90
scores[4] = 58

Read for (i = 0; i < 5; i++) in three parts, separated by semicolons:

  • i = 0: start with i at 0, the first index.
  • i < 5: keep going while i is less than 5, the size. When i reaches 5 the loop stops.
  • i++: after each pass, add 1 to i. It is short for i = i + 1.

The statements in the curly braces run once for each value of i. Change the 5 to 3 and only the first three scores print. Change it back. With 30 students, you would change the array size and the 5 in the loop, and nothing else.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};
    int i;

    for (i = 0; i <= 5; i++)
    {
        printf("scores[%d] = %d\n", i, scores[i]);
    }
    return 0;
}

Break it on purpose: use <= in the loop

Change i < 5 to i <= 5 (“less than or equal to”). Build and run. There is no error and no warning. On our test computer it printed:

scores[0] = 72
scores[1] = 85
scores[2] = 64
scores[3] = 90
scores[4] = 58
scores[5] = 0

Six lines from a five-box array. With <=, the loop also runs when i is 5, and reads scores[5], a box that does not exist. The value you see is whatever happens to be in the memory just after the array, so your number may be different, and it may change from run to run. This is called an off-by-one error. For an array of size 5, the loop test is i < 5, never i <= 5. Change it back.

Try it: total and average

The loop can do more than print. Here it adds each score to a running total, then divides by 5:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};
    int i;
    int total = 0;
    float average = 0;

    for (i = 0; i < 5; i++)
    {
        total = total + scores[i];
    }

    average = total / 5;

    printf("Total: %d\n", total);
    printf("Average: %.2f\n", average);
    return 0;
}
Total: 369
Average: 73.00

The total is right, but 369 ÷ 5 is 73.8, not 73.00. You have seen this before in the int vs float lesson. total and 5 are both int, so C does whole-number division and truncates the answer to 73 before it is stored in the float. Storing it in a float afterwards cannot bring the .8 back. Make one side of the division a decimal number:

    average = total / 5.0;
Total: 369
Average: 73.80

Trace the loop once by hand: total starts at 0, then becomes 72, 157, 221, 311 and finally 369. If you want to watch it happen, set a breakpoint on the total = total + scores[i]; line and add i and total as watches, as in the debugging lesson.

Try it: read the scores in

Now let the user type the scores. Each element is an ordinary int, so scanf needs its location, with &, just like &x in the scanf lesson:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {0};
    int i;
    int total = 0;

    for (i = 0; i < 5; i++)
    {
        printf("Enter score %d: ", i + 1);
        scanf("%d", &scores[i]);
    }

    for (i = 0; i < 5; i++)
    {
        total = total + scores[i];
    }

    printf("You entered: %d %d %d %d %d\n", scores[0], scores[1], scores[2], scores[3], scores[4]);
    printf("Average: %.2f\n", total / 5.0);
    return 0;
}

Build and run. Type each score and press Enter:

Enter score 1: 72
Enter score 2: 85
Enter score 3: 64
Enter score 4: 90
Enter score 5: 58
You entered: 72 85 64 90 58
Average: 73.80

&scores[i] means “the location of box i”. Each element is one int box, so scanf needs the & in front of it, exactly as for a single variable. The prompt shows i + 1 so that people see 1 to 5, while the program uses indexes 0 to 4.

Try it: one past the end

Replace main with this short program, which asks for the element after the last one:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};

    printf("scores[4] = %d\n", scores[4]);
    printf("scores[5] = %d\n", scores[5]);
    return 0;
}

Break it on purpose: ask for scores[5]

Build and run. On our test computer, GCC gave no error and no warning (even with -Wall), and printed:

scores[4] = 58
scores[5] = 0

C does not check indexes. It works out where box 5 would be and reads that memory, even though it is not part of the array. This is out of bounds access, and the C standard calls the result undefined behaviour: it may print a garbage number, it may print 0 and look fine, it may give a different answer on another computer, or the program may crash. Writing out of bounds, such as scores[5] = 99;, is worse, because it can change some other variable without warning. Keeping every index between 0 and size − 1 is your job, not the compiler’s.

Try it: copy one array into another

Suppose you want a backup of the scores before changing them:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int scores[5] = {72, 85, 64, 90, 58};
    int backup[5];

    backup = scores;
    printf("backup[0] = %d\n", backup[0]);
    return 0;
}

Break it on purpose: copy an array with =

Build it. The build stops with:

main.c:9:12: error: assignment to expression with array type

After it is declared, a whole array cannot be assigned with =. Instead, copy the elements one at a time with the loop.

Replace the backup = scores; line with a loop (and declare int i; with the other variables):

    for (i = 0; i < 5; i++)
    {
        backup[i] = scores[i];
    }
backup[0] = 72

Common mistakes

  • Using index 5 in an array of size 5. The last index is always size − 1.
  • Writing i <= 5 instead of i < 5 in the loop.
  • Forgetting that total / 5 with two ints truncates. Use 5.0.
  • Leaving out the & in scanf("%d", &scores[i]);.
  • Trying to copy or assign a whole array with =.

Key terms

  • Array: a row of variables of the same type under one name, such as int scores[5].
  • Element: one box in an array, such as scores[2].
  • Size: the number of elements, given in the declaration. It cannot change while the program runs.
  • Index: the position of an element, counted from 0. Valid indexes run from 0 to size − 1.
  • Initialiser list: values in curly braces that fill an array as it is declared, such as {72, 85, 64, 90, 58}.
  • for loop: repeats a block of statements; here, once for each index from 0 to size − 1.
  • Off-by-one error: a loop or index that goes one step too far (or stops one step short).
  • Out of bounds: using an index outside the array. C does not check it; the result is undefined behaviour.

Quick check

  1. An array is declared float temps[7];. What are its first and last valid indexes?

    Show answer

    temps[0] and temps[6].

  2. What is in each element after int counts[4] = {3, 9};?

    Show answer

    counts[0] is 3, counts[1] is 9, and counts[2] and counts[3] are 0.

  3. A program prints scores[5] from a size-5 array and gets 0, with no error. Is the program correct?

    Show answer

    No. scores[5] is out of bounds. C does not check it, so the 0 is just whatever was in that memory: undefined behaviour that may print something else, or crash, elsewhere.

  4. A total of 47 is divided by 4 with average = total / 4; and average is a float. What prints with %.2f, and how do you fix it?

    Show answer

    11.00, because int ÷ int truncates. Use total / 4.0 to get 11.75.

  5. Why does scanf("%d", &scores[i]); need the &?

    Show answer

    Each element is an ordinary int variable, and scanf needs its location, just like &x.

Coming up: text is an array too

Every array in this lesson held numbers, but the type in each box can be anything, including char, a single character. Put a row of characters in an array and you have a word. In the next lesson you will see that a string in C is just an array of char, so everything here, from indexes starting at 0 to = refusing to copy, carries straight over.

Part of the Introduction to C series. Next: Strings in C: char Arrays, %s, fgets, and strlen

Strings in C: char Arrays, %s, fgets, and strlen

In the last lesson, Arrays in C: Storing Many Values Under One Name, you stored many numbers under one name in an array. A string is the same idea: an array of char, one character in each box. Every variable so far has held a number, but programs work with text all the time: names, cities, answers. In this lesson you store one character, then a whole word, then read a name from the keyboard and break it on purpose. Along the way you find out what the \0 escape sequence from the printf lesson is for, and meet the input buffer from Using Library Functions: #include, getch(), and the Input Buffer again.

In this lesson you will

  • Store a single character in a char variable and print it with %c
  • Store a word as a string: a row of characters ending in '\0'
  • Print a string with %s and read one with scanf, and find out why it stops at a space
  • Read a whole line safely with fgets, and spot the Enter key it keeps
  • Use strlen and strcpy from string.h, and learn why = cannot copy a string

Start a new project for this lesson. Copy 004-ArraysCProgram to a new folder named 005-StringsCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.

Try it: one character

The data-type table in the int vs float lesson listed char, a type that holds a single character, printed with %c. Try it:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char initial = 'K';

    printf("Your initial is %c\n", initial);
    return 0;
}
Your initial is K

Notice the single quotes. 'K' is a character literal: exactly one character. Double quotes make a string literal, which can hold many. Change 'K' to "K" and the build complains. Change it back.

Try it: a whole word

A char holds one character, so a name needs a whole row of them. Replace main with this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char name[20] = "Ken";

    printf("Hello, %s!\n", name);
    printf("Letters: %c %c %c\n", name[0], name[1], name[2]);
    printf("After the last letter: %d\n", name[3]);

    name[0] = 'B';
    printf("Hello, %s!\n", name);
    return 0;
}
Hello, Ken!
Letters: K e n
After the last letter: 0
Hello, Ben!

What just happened

char name[20] declares an array, just like int scores[5] in the arrays lesson, except that each of its 20 boxes holds a char instead of an int. You reach each one by its index in square brackets, and counting still starts at 0, so name[0] is the first character and name[19] is the last.

Initialising the array with "Ken" fills it like this:

Index01234 to 19
Contents'K''e''n''\0''\0' (unused)

Straight after the last letter sits '\0', the null character. Printed as a number with %d, it shows as 0. This is the end marker that the escape-sequence table promised to explain: in C, a string is a row of characters that ends with '\0'. %s tells printf to start at the first character and keep printing until it reaches the '\0'. Changing name[0] to 'B' changed one box, so the whole word became Ben.

Because the end marker takes up one place, an array of 20 characters can hold a string of at most 19 characters.

Try it: ask for the name

Now let the user type the name. scanf reads a string with %s:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char name[20] = "";
    char colour[20] = "";

    printf("What is your name?\n");
    scanf("%s", name);
    printf("What is your favourite colour?\n");
    scanf("%s", colour);

    printf("Hello, %s! Your favourite colour is %s.\n", name, colour);
    return 0;
}

Build and run. Type Ken and press Enter, then type blue and press Enter:

What is your name?
Ken
What is your favourite colour?
blue
Hello, Ken! Your favourite colour is blue.

Look closely: there is no & in front of name. In the scanf lesson, scanf needed &x, the location of the variable. The name of an array already stands for the location of its first character, so name on its own is enough. Add an & out of habit and GCC warns:

warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[20]' [-Wformat=]

If you tried that, remove the & again and rebuild.

Break it on purpose: type a name with a space

Run the program again. At the first question type Ken Smith and press Enter. Observe: the program does not wait for the colour. It answers straight away:

What is your name?
Ken Smith
What is your favourite colour?
Hello, Ken! Your favourite colour is Smith.

Your surname has become your favourite colour.

%s in scanf reads one word. It stops at the first space, tab or Enter. So name got Ken, and the rest of the line, Smith and the Enter, stayed behind in the input buffer, the same waiting area that caught the held-down key in the previous lesson. The second scanf found Smith already waiting and took it without asking.

Try it: read the whole line with fgets

To read everything the user typed, up to and including the Enter, use fgets (“file get string”). Here the “file” is stdin, the standard input, which is normally the keyboard. The program also uses strlen (“string length”), which counts the characters before the '\0'. It is declared in string.h, so the program includes that header:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char name[20] = "";

    printf("What is your full name?\n");
    fgets(name, sizeof(name), stdin);

    int length = strlen(name);
    printf("Hello, %s!\n", name);
    printf("Your name has %d characters.\n", length);
    return 0;
}

Run it and type Ken Smith. Observe two odd things:

What is your full name?
Ken Smith
Hello, Ken Smith
!
Your name has 10 characters.

The ! has dropped onto the next line, and Ken Smith has 9 characters (the space counts), not 10. Both clues point to the same thing: fgets keeps the Enter key. The string in memory is Ken Smith\n. That hidden \n is the tenth character, and printing it moves the ! to a new line.

fgets takes three things: where to store the text, the size of the array (sizeof(name), here 20), and where to read from (stdin). Because it knows the size, it stores at most 19 characters plus the '\0'.

To remove the Enter, add one line after the fgets. strcspn(name, "\n"), also from string.h, counts the characters before the first \n, which is exactly the index where the \n sits. Putting '\0' there ends the string one place earlier. Rebuild and run with Ken Smith again:

    fgets(name, sizeof(name), stdin);
    name[strcspn(name, "\n")] = '\0';   /* remove the Enter */
What is your full name?
Ken Smith
Hello, Ken Smith!
Your name has 9 characters.

Now try a long name, such as Alexandria Montgomery-Smith. The program prints Hello, Alexandria Montgome! (19 characters). fgets stopped when the array was full and left the rest in the input buffer. Cut off, but safe.

Why the size matters: buffer overflow. scanf("%s", name) does not know how big name is. Type more than 19 characters and it writes past the end of the array, over whatever memory comes next. This is a buffer overflow. The program may crash, quietly change other variables, or work on one computer and fail on another, and attackers use overflows to break into systems. fgets is given the size, so it cannot overflow. (Old books mention a function called gets. It has the same problem and has been removed from C. Never use it.)

Try it: give the string a new value

You can set a number with = at any time, so it seems natural to do the same with a string:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char name[20] = "Ken";
    printf("Before: %s\n", name);

    name = "Kenneth";
    printf("After: %s\n", name);
    return 0;
}

Break it on purpose: copy a string with =

Build it. The build stops with:

main.c:10:10: error: assignment to expression with array type

= worked in the declaration, char name[20] = "Ken";, because that is initialisation: the array is filled as it is created. Afterwards, C does not let you assign a whole array with =.

To copy text into an existing array, use strcpy (“string copy”) from string.h. It copies the characters one by one, including the '\0'. Replace the = line with:

    strcpy(name, "Kenneth");
Before: Ken
After: Kenneth

Read strcpy(name, "Kenneth") as “copy "Kenneth" into name”: the destination comes first, like the left side of =. Like scanf("%s"), strcpy does not check the size, so the destination must be big enough.

Key terms

  • char: a data type that holds a single character, printed with %c.
  • Character literal: one character in single quotes, such as 'K'.
  • Array: a row of variables of the same type under one name, such as char name[20].
  • Index: the position of an item in an array, counted from 0, as in name[0].
  • String: in C, a row of characters in a char array, ending with '\0'.
  • Null character ('\0'): the character with value 0 that marks the end of a string.
  • %s: the format specifier for a string, in both printf and scanf.
  • fgets: reads a whole line of input, up to a size limit, and keeps the Enter (\n).
  • strlen: a string.h function that counts the characters in a string, not including the '\0'.
  • Buffer overflow: writing past the end of an array, into memory that belongs to something else.

Quick check

  1. How big must a char array be to hold the string "Hello"?

    Show answer

    At least 6: five letters plus the '\0' at the end.

  2. A program uses scanf("%s", city); and the user types Port of Spain. What ends up in city, and where is the rest?

    Show answer

    Port. %s stops at the first space, and of Spain plus the Enter wait in the input buffer for the next read.

  3. After fgets(name, sizeof(name), stdin) reads Ana, strlen(name) says 4. Why?

    Show answer

    fgets keeps the Enter, so the string is Ana\n. Remove it with name[strcspn(name, "\n")] = '\0';

  4. city = "Paris"; gives assignment to expression with array type. How do you fix it?

    Show answer

    Use strcpy(city, "Paris"); and add #include <string.h>. Arrays cannot be assigned with = after they are declared.

Part of the Introduction to C series. Next: Storing Records with Parallel Arrays

Updates

2026/10/07
– Moved after the new Arrays lesson and added a link back to it.

Using Library Functions: #include, getch(), and the Input Buffer

Your addition program prints its welcome message and then rushes straight on to the first question. It would be friendlier to pause with “Press any key to continue…” and wait. C has no built-in command for that, but libraries do. In this lesson you try to call a function that does not exist, find out how C locates the functions you use, and meet a sneaky problem with the keyboard.

In this lesson you will

  • See what happens when you call a function that is not declared anywhere
  • Use #include to bring in a library’s declarations
  • Use getch() from conio.h to wait for a key press, and learn why it only works on Windows
  • Compare input that echoes with input that does not
  • Watch a held-down key leak through the input buffer into scanf

Try it: guess a function name

Add a “Press any key” line to WelcomeMessage, followed by a call to a function that sounds right, ReadKey():

#include <stdio.h>
#include <stdlib.h>

void WelcomeMessage(void);

int main()
{
    WelcomeMessage();

    float x = -9999;
    float y = -9999;

    printf("Please enter a value for x:\n");
    scanf("%f", &x);
    printf("Please enter a value for y:\n");
    scanf("%f", &y);

    printf("The sum of %.2f and %.2f is %.2f\n", x, y, x + y);
    return 0;
}

void WelcomeMessage(void)
{
    printf("Welcome to the addition program\n\n");
    printf("Press any key to continue...\n\n");
    ReadKey();
}

Break it on purpose: call a function that does not exist

Build it. With GCC 14 the build stops with:

main.c:26:5: error: implicit declaration of function 'ReadKey' [-Wimplicit-function-declaration]

Older compilers, including the GCC bundled with many Code::Blocks installs, may only warn about the implicit declaration. The build then fails one step later, when the linker cannot find the function’s code anywhere:

undefined reference to `ReadKey'
collect2: error: ld returned 1 exit status

ReadKey exists in some other languages, but not in standard C. (In Pascal and in C#, for example, there is a function called ReadKey.) Guessing names does not work. You need to know which library a function lives in.

Including a random header does not help either. Add #include <string.h> at the top and build again, and you get the same error. string.h declares functions for working with text, and none of them is called ReadKey.

Try it: getch() from conio.h

On Windows, the function you want is getch(). It waits for a single key press and returns it. It is declared in a header file called conio.h (“console input/output”). Add the #include line and replace ReadKey():

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

void WelcomeMessage(void);

int main()
{
    WelcomeMessage();

    float x = -9999;
    float y = -9999;

    printf("Please enter a value for x:\n");
    scanf("%f", &x);
    printf("Please enter a value for y:\n");
    scanf("%f", &y);

    printf("The sum of %.2f and %.2f is %.2f\n", x, y, x + y);
    return 0;
}

void WelcomeMessage(void)
{
    printf("Welcome to the addition program\n\n");
    printf("Press any key to continue...\n\n");
    getch();
}

Build and run. The program stops after the welcome message. Press any key, for example j, and it carries on to the first question:

Welcome to the addition program

Press any key to continue...

Please enter a value for x:

Notice that the j you pressed did not appear on the screen, and you did not have to press Enter. Compare that with scanf, where everything you type is shown (echoed) and nothing happens until you press Enter. getch() reads one key straight away, without echo. That makes the pause feel smooth.

Windows only. conio.h and getch() are not part of standard C. They come with Windows compilers such as the MinGW GCC that Code::Blocks installs. On macOS or Linux the build fails with fatal error: conio.h: No such file or directory. A portable alternative is the standard function getchar() from stdio.h. It echoes, and it waits for Enter, so change the message to “Press Enter to continue…”.

What just happened

Functions such as printf, scanf and getch are library functions. Someone else wrote and compiled them, and they are supplied with your compiler. To use one, the compiler needs its declaration, its prototype, exactly as with your own functions in the earlier lessons. Libraries supply their prototypes in header files (.h files). The line #include <conio.h> tells the preprocessor to paste the contents of that header into your file before compiling, so the compiler knows what getch is. Then the linker joins your code to the library’s compiled code.

That explains both errors with ReadKey. There was no declaration, so the compiler complained. On older compilers that let it through, there was no compiled code to link to, so the linker complained instead. It also explains why stdio.h has been at the top of every program since the first lesson: it declares printf and scanf.

Try it: hold the key down

Break it on purpose: a key press that leaks

Run the getch version again. This time, at the “Press any key” pause, press the 8 key and hold it down for a moment before letting go. Observe: the first question appears with 8s already typed in, and they become the start of the value for x:

Please enter a value for x:
88815

Here the user held down 8, then typed 15 and pressed Enter, so x became 88815.

Holding a key makes it repeat. getch() takes only the first 8. The repeats are stored in the input buffer, a waiting area for keyboard input that has not been read yet. When scanf runs next, it reads from that same buffer, finds the 8s waiting, and treats them as the start of the number.

The simplest fix is to tap the key rather than hold it. On Windows you can also throw away any extra key presses straight after the getch(), using kbhit() (also from conio.h), which reports whether a key is waiting:

    getch();
    while (kbhit())   /* while more key presses are waiting... */
    {
        getch();      /* ...read them and throw them away */
    }

Key terms

  • Library function: a ready-made function supplied with the compiler, such as printf or getch.
  • Header file (.h): a file of declarations (prototypes) for a library’s functions.
  • #include: a preprocessor instruction that inserts a header file into your code before compiling.
  • Preprocessor: the step before compiling that handles lines beginning with #.
  • Linker: the step after compiling that joins your code with library code to make the executable.
  • Echo: showing typed characters on the screen as they are entered.
  • Input buffer: where keyboard input waits until the program reads it.
  • Non-standard: not part of the C standard, so only available on some systems (like conio.h).

Quick check

  1. The build reports “implicit declaration of function” for a library function. What is the usual fix?

    Show answer

    #include the header that declares it, for example stdio.h for printf.

  2. Name two differences between getch() and scanf("%f", &x) from the user’s point of view.

    Show answer

    getch() does not echo the key, and it does not wait for Enter. scanf echoes what you type and waits for Enter.

  3. Your friend on a Mac gets fatal error: conio.h: No such file or directory. Why?

    Show answer

    conio.h is non-standard and Windows-only. Use a standard function such as getchar() instead.

  4. Why can holding down a key at a getch() pause change the value that the next scanf reads?

    Show answer

    The repeated key presses wait in the input buffer, and scanf reads them as the start of its input.

Optional: a recorded demonstration of these steps starts around 38:30. getch() and the input-buffer problem follow from about 42:30.

Part of the Introduction to C series. Next: Arrays in C: Storing Many Values Under One Name

Debugging in Code::Blocks: Breakpoints, Step Over, Step Into, Watches

In the previous lesson you found the copy-paste bug by spotting -9999 in the output. That worked because the program was tiny. In real programs you need a way to stop the program part-way through and look inside it. That tool is the debugger, and Code::Blocks has one built in. In this lesson you use it to watch the copy-paste bug happen, one line at a time.

In this lesson you will

  • Set a breakpoint and start a program in Debug mode
  • Step through code with Next line and Step into, and jump ahead with Continue
  • Inspect variables in the Watches window
  • Discover that a float cannot store 15.1 exactly

Try it: set up the buggy program

Open 002-UserInputCProgram and put the copy-paste bug back in, so that the second scanf reads into &x:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float x = -9999;
    float y = -9999;

    printf("Please enter a value for x:\n");
    scanf("%f", &x);
    printf("Please enter a value for y:\n");
    scanf("%f", &x);

    float sum = x + y;
    printf("The sum of %.2f and %.2f is %.2f\n", x, y, sum);
    return 0;
}

Check that the build target in the toolbar is set to Debug (not Release). The Debug target builds your program with extra information (GCC’s -g option) that lets the debugger match the running program to your lines of code.

Try it: breakpoints

A breakpoint is a marker that says “pause here”. Click in the margin just to the right of the line number beside the first scanf (line 10). A red dot appears. (You can also put the cursor on the line and press F5 to toggle a breakpoint.) Add a second breakpoint on the line float sum = x + y;.

Break it on purpose: breakpoints that are never hit

With both breakpoints set, click the usual Build and run button. Observe: the program runs from start to finish as if the breakpoints were not there.

Breakpoints only work when the program runs under the debugger. Stop the program. Then choose Debug → Start / Continue (F8, or the red arrow on the debugger toolbar).

This time the program starts, prints the first prompt, and stops. A yellow arrow appears in the margin at your first breaThe yellow arrow marks the line that will run next. It has not run yet. That is why nothing has been typed into the console so far.

Try it: step and watch

Open Debug → Debugging windows → Watches. It lists the local variables and their current values. Right now x and y both show -9999.

  1. Choose Debug → Next line (F7). The scanf runs and waits for you, so switch to the console, type 15.1 and press Enter. The yellow arrow moves down one line.
  2. Look at the Watches window. x now shows something like 15.1000004. Keep that in mind for later.
  3. Choose Debug → Start / Continue again. The program runs until it reaches the next breakpoint. On the way it asks for y: type 300.
  4. Look at the Watches window again. x has changed to 300, but y is still -9999. You have just watched the bug happen: the value meant for y went into x.
  5. Choose Debug → Stop debugger, fix the second scanf to use &y, and debug once more to confirm that both values arrive where they should.

What just happened

The debugger gives you three ways to move forward:

  • Next line (often called step over) runs the current line completely, then pauses on the next one. If the line calls a function, the whole function runs in one go.
  • Step into (Shift+F7) also runs one line, but if that line calls a function you wrote, it goes inside the function and pauses on its first line. This becomes useful in the next lesson, when you write your own functions. Library functions such as printf have no source code for the debugger to show, so stepping into them usually behaves like Next line.
  • Continue runs at full speed until the next breakpoint, or until the program ends.

One more surprise: when the program finishes under the debugger, the console window closes straight away, before you can read the output. A simple fix is to put a breakpoint on the return 0; line. The program then pauses there, with all of its output still on screen.

Name it: floats are not exact

Why did the Watches window show 15.1000004 instead of 15.1? A float stores numbers in binary, and most decimal fractions, including 0.1, cannot be written exactly in binary. In the same way, 1/3 cannot be written exactly in decimal (0.3333…). The computer stores the nearest value it can. You can see the stored value by asking printf for more decimal places than usual:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float x = 15.1;
    printf("%.2f\n", x);
    printf("%.10f\n", x);
    return 0;
}
15.10
15.1000003815

For everyday output, %.2f hides the tiny difference. Just remember never to expect a float to be exactly equal to a decimal value like 15.1. This matters later, when you start comparing values.

Key terms

  • Debugger: a tool that runs your program under control, so you can pause it and inspect it. Code::Blocks uses GDB.
  • Breakpoint: a marker on a line where the program pauses when run in Debug mode.
  • Next line (step over): run the current line, including any function it calls, and pause on the next line.
  • Step into: if the current line calls one of your functions, pause inside that function.
  • Continue: run until the next breakpoint.
  • Watches: a window showing the current values of variables.
  • Debug target: a build configuration that includes debugging information (-g).

Quick check

  1. You set a breakpoint, click Build and run, and the program never pauses. Why?

    Show answer

    Breakpoints only work under the debugger. Start the program with Debug → Start / Continue.

  2. The yellow arrow points at y = 6;. Has y been set to 6 yet?

    Show answer

    No. The arrow marks the line that will run next. Choose Next line, and then y becomes 6.

  3. What is the difference between Next line and Step into on a line that calls one of your own functions?

    Show answer

    Next line runs the whole function and stops on the following line. Step into goes inside the function and stops on its first line.

  4. Why might the Watches window show 2.0999999 for a float set to 2.1?

    Show answer

    Most decimal fractions cannot be stored exactly in binary, so the float holds the closest value it can.

Optional: a recorded demonstration of these steps starts around 2:10. Next line and Step into are demonstrated from about 18:00.

Part of the Introduction to C series. Next: Your First Function: void, Declarations, and Definitions

Reading Input with scanf (and Defensive Initialization)

Until now, the numbers your program adds are fixed in the code. Every time you want different numbers, you have to edit and rebuild. In this lesson the program asks the user for the numbers instead. Then you make one of the most common beginner mistakes on purpose, and use a simple trick to make it stand out.

In this lesson you will

  • Start a new project by copying the previous one
  • Read numbers from the keyboard with scanf
  • Meet the address-of operator, &
  • Use defensive initialisation to expose a logical error

Before you start: copy your project. Keep 001-FirstCProgram as it is and continue in a copy. That way you can always look back at a working version.

  1. Close the project in Code::Blocks. In File Explorer, copy the 001-FirstCProgram folder and paste it next to the original. Rename the copy 002-UserInputCProgram.
  2. Open the .cbp file inside the new folder. Choose File → Save project as… and save it in the new folder as 002-UserInputCProgram.cbp. Then delete the old 001-FirstCProgram.cbp from the new folder, so you cannot open it by accident.
  3. Open Project → Properties…. On the Project settings tab, change the Title to 002-UserInputCProgram.
  4. On the Build targets tab, change the Output filename for both Debug and Release, for example to bin\Debug\002-UserInputCProgram.exe. If you skip this, your new project still builds a program called 001-FirstCProgram.exe, which gets confusing quickly.

Try it: ask the user for the numbers

Replace main in your new project with the version below. The two scanf lines are new. Notice the & in front of each variable name, and the starting value of -9999. Both are explained shortly.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float x = -9999;
    float y = -9999;

    printf("Please enter a value for x:\n");
    scanf("%f", &x);
    printf("Please enter a value for y:\n");
    scanf("%f", &y);

    float sum = x + y;
    printf("The sum of %.2f and %.2f is %.2f\n", x, y, sum);
    return 0;
}

Build and run. The program prints the first prompt and then waits. Type 15.1 and press Enter, then type 300 and press Enter:

Please enter a value for x:
15.1
Please enter a value for y:
300
The sum of 15.10 and 300.00 is 315.10

Run it again with different numbers. The program no longer needs rebuilding to add new values.

What just happened

scanf is formatted input, the mirror image of printf. Its first argument is a format string: "%f" means “read the characters the user types and convert them into a float”. Then it needs to know where to put the result.

That is the job of &, the address-of operator. x on its own means “the value inside x”. &x means “the location of x in memory”. printf only needs values to display, but scanf has to change your variable, so you must tell it where the variable lives.

Leave out the & and GCC warns you, and Code::Blocks shows a similar message in its build log:

warning: format '%f' expects argument of type 'float *', but argument 2 has type 'double' [-Wformat=]

Treat that warning as an error and fix it. If you run the program anyway, scanf tries to write to a nonsense location, and the program may crash.

Try it: the copy-paste trap

When you write the second prompt, it is tempting to copy the first two lines, paste them, and change x to y. Now forget to change one of them on purpose. Edit the second scanf so that it still reads into &x:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float x = -9999;
    float y = -9999;

    printf("Please enter a value for x:\n");
    scanf("%f", &x);
    printf("Please enter a value for y:\n");
    scanf("%f", &x);

    float sum = x + y;
    printf("The sum of %.2f and %.2f is %.2f\n", x, y, sum);
    return 0;
}

Break it on purpose: read y into x

Build the program above: no errors, no warnings. Run it and enter 15.1 and 300 again. Observe:

Please enter a value for x:
15.1
Please enter a value for y:
300
The sum of 300.00 and -9999.00 is -9699.00

The program asked for y, but the 300 went into x and overwrote the 15.1. y was never touched, so it still holds its starting value.

Notice how loudly the mistake shows up. -9999 is not a number anyone would type by accident, so the moment it appears in the output you know a variable was never filled in. Choosing an obviously “impossible” starting value on purpose is called defensive initialisation.

Without it, float y; would contain whatever bits happened to be left in that memory. That value is indeterminate (unpredictable): sometimes zero, sometimes a strange number. A bug that sometimes hides is much harder to find than one that always shouts. Fix the second scanf back to &y, and test again with numbers whose sum you know.

Key terms

  • scanf: reads formatted input from the keyboard and stores it in variables.
  • Address-of operator (&): gives the memory location of a variable, e.g. &x.
  • Initialisation: giving a variable a starting value when you declare it.
  • Defensive initialisation: using a deliberately unusual starting value (such as -9999) so that a variable that is never filled in is easy to spot.
  • Indeterminate value: the unpredictable contents of a local variable that has not been initialised.

Quick check

  1. Why does scanf need &x while printf only needs x?

    Show answer

    scanf has to store a new value in the variable, so it needs the variable’s address. printf only reads the value to display it.

  2. A program prints The sum of 8.00 and -9999.00 is -9991.00. What has most likely gone wrong?

    Show answer

    The second variable was never filled in. Its scanf probably reads into the wrong variable, or is missing.

  3. Does the copy-paste mistake cause a syntax error or a logical error?

    Show answer

    A logical error. The code is valid C, so it builds without warnings, but it does the wrong thing.

  4. After copying a project folder, what two names should you change in Project → Properties?

    Show answer

    The project Title (Project settings tab) and the Output filename of each build target (Build targets tab).

Optional: a recorded demonstration of these steps starts around 0:50. Copying the project to a new folder follows at about 5:20.

Part of the Introduction to C series. Next: Debugging in Code::Blocks: Breakpoints, Step Over, Step Into, Watches

printf, String Literals, and Escape Sequences

In the previous lesson you got Hello world running in Code::Blocks and changed it to print a name. In this lesson you look closely at the one line that does the work: printf. You will remove a tiny piece of it, see what breaks, and use that to name two important ideas: string literals and escape sequences.

In this lesson you will

  • Find out what printf means and what the text inside the quotes is called
  • See what \n does, and what goes wrong without it
  • Try three more escape sequences: \t, \r and (briefly) \0
  • Print a backslash and a double quote

Try it: the line that does the work

Open your 001-FirstCProgram project. Your main.c should look like this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello, my name is Ryu\n");
    return 0;
}

printf stands for print formatted. It sends text to the console window. Everything between the double quotes is printed exactly as written, apart from a few special combinations that start with a backslash. One of those sits right at the end: \n.

Now change one thing. Delete the \n at the end of the message, then Build and run. Look carefully. With only one line of output the difference is small and easy to miss. To see it clearly, the program needs a second printf.

Replace the body of main with two messages, the kind of welcome an addition program might show. Leave out the \n on purpose:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Welcome to the addition program");
    printf("I hope you enjoy this program");
    return 0;
}

Break it on purpose: two messages, no newlines

Build and run the program above. Observe: both messages are squashed onto one line with no space between them:

Welcome to the addition programI hope you enjoy this program

The program built with no errors, yet the output is not what you meant. Now add \n to the end of each message, then build and run again.

Remember: if the output looks the same after an edit, check that you clicked Build and not just Run.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Welcome to the addition program\n");
    printf("I hope you enjoy this program\n");
    return 0;
}
Welcome to the addition program
I hope you enjoy this program

What just happened

The text in double quotes is called a string literal. A string is a group of characters, and literal means it is printed exactly as it appears in your code. printf does not add a new line for you. It prints exactly what you ask for and leaves the cursor wherever the text ended, so the next printf carries on from that spot.

To ask for a new line you use an escape sequence: a backslash followed by a character. Together they stand for one special character that would be hard to type directly. \n is the newline character. It moves the cursor to the start of the next line.

Try it: a newline in the middle

An escape sequence can go anywhere in the string, not just at the end. Put one after Hello,:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello,\n my name is Ryu\n");
    return 0;
}
Hello,
 my name is Ryu

Look at the start of the second line. There is a space before my, because the string contains a space right after \n. A string literal prints every character, spaces included.

Try it: tab and carriage return

Replace the \n after Hello, with \t, then build and run:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello,\t my name is Ryu\n");
    return 0;
}
Hello,   my name is Ryu

\t is a tab. It moves the cursor forward to the next tab stop, just like pressing the Tab key while typing.

Now try \r:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello,\r my name is Ryu\n");
    return 0;
}
 my name is Ryu

Where did Hello, go? \r is the carriage return. It sends the cursor back to the start of the same line without moving down, so the rest of the text is printed over the top of Hello,. The exact behaviour of \r can differ between systems and consoles. That is one reason you will use \n almost all the time.

Name it: common escape sequences

Escape sequenceNameWhat it does
\nnewlineMoves to the start of the next line
\thorizontal tabMoves forward to the next tab stop
\rcarriage returnMoves back to the start of the current line
\\backslashPrints a single \
\"double quotePrints " without ending the string
\0null characterMarks the end of a string in memory (more on this later in the series)

A backslash starts an escape sequence, and a double quote ends a string, so you need an escape sequence to print either of them:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Name:\tRyu\n");
    printf("A backslash: \\ and a quote: \"\n");
    return 0;
}
Name:   Ryu
A backslash: \ and a quote: "

Key terms

  • printf: “print formatted”, the standard C function (from stdio.h) that writes text to the console.
  • String: a group of characters.
  • String literal: a string written directly in your code between double quotes, such as "Hello, my name is Ryu\n".
  • Escape sequence: a backslash followed by a character, standing for one special character such as newline or tab.
  • Newline (\n), tab (\t), carriage return (\r): three escape sequences you tried in this lesson.

Quick check

  1. What is printed by printf("Hi"); followed by printf("there\n");?

    Show answer

    Hithere on one line, then a new line. The first printf has no \n and no space, so the second message carries on straight after it.

  2. Why does printf("Hello,\n my name is Ryu\n"); print a space at the start of the second line?

    Show answer

    The string literal contains a space right after \n, and every character in a string literal is printed exactly as written.

  3. How would you print the text She said "hi" with the quote marks?

    Show answer

    Escape the inner quotes: printf("She said \"hi\"\n");

  4. You added a \t, but the output looks exactly the same as before. What should you check first?

    Show answer

    That you clicked Build (or Build and run). Clicking only Run starts the old executable, which was built before your change.

Optional: a recorded demonstration of these steps starts around 19:40.

Part of the Introduction to C series. Next: Statements, Semicolons, and Whitespace: How the Compiler Reads Your Code

Your First C Program in Code::Blocks: Projects, Build, and Run

This is the first lesson in the Introduction to C series. It does not begin with a long list of rules. Instead, you open Code::Blocks, get a program running, and then change one small thing at a time and watch what happens. Along the way you will make a couple of mistakes on purpose, because seeing what goes wrong and why is one of the fastest ways to learn. If you are studying CAPE Computer Science Unit 1, or starting C on your own, open Code::Blocks and follow each step.

In this lesson you will

  • Create a Code::Blocks project (not just a file) for a C console program
  • Choose where the project lives on disk, and learn why the folder path should be short
  • Tell the difference between Build, Run and Build and run
  • Read the build log and the “Process returned 0” message
  • Recover when the IDE seems to stop responding

Try it: create your first project

Whenever you write C in Code::Blocks, create a project, not a loose file. A project keeps your source code, your settings and your compiled program together in one folder.

  1. Open Code::Blocks and choose File → New → Project…
  2. Choose Console application, then Go. Click Next on the welcome page of the wizard.
  3. When asked for the language, choose C, not C++. (Some other beginner IDEs, such as Dev-C++, lean towards C++ by default. In this series you write C.)
  4. Give the project a title: 001-FirstCProgram. The number at the front keeps your projects in order (001, 002, 003…) as the series goes on. Capitalising the first letter of each word, as in FirstCProgram, is called upper camel case (also called PascalCase).
  5. Choose a folder to create the project in. Pick one close to the top of your drive, and use a sensible, school-appropriate folder name.
  6. On the next page, leave the compiler as GNU GCC Compiler with both Debug and Release ticked. If you installed Code::Blocks with MinGW, this is already filled in for you. Click Finish.

A good example of a short project location:

C:\CPrograms\2026-2027\001-FirstCProgram

Why keep the path short? Windows (and some tools) can run into trouble when a full file path is longer than about 255 characters. The same problem can stop a web browser from uploading an assignment buried deep inside many folders. If a project sits inside folder after folder, you may later see strange compile or debug errors. A short path avoids that.

In the Projects panel on the left, expand Sources and double-click main.c. It opens in a tab, and Code::Blocks has already written a first program for you:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello world!\n");
    return 0;
}

Try it: build, then run

Find the build toolbar near the top of the window. For now, use the two buttons separately so that you can see what each one does:

  • Build (the gear icon) turns your source code into a program the computer can run.
  • Run (the green play arrow) starts the program that was last built.
  • Build and run (gear plus arrow) does both, one after the other.

Click Build and look at the Build log at the bottom of the screen. You should see a line ending in 0 error(s), 0 warning(s), along with how long the build took. Now click Run. A console window opens:

Hello world!

Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.

The “Process returned 0” line comes from return 0; at the end of main. By convention, a program that finishes normally returns 0. (Your execution time will be different.) Press a key to close the window.

Now change one thing. Show that you are in charge of this code by changing the message to a name. Use your own name, or Ken as in this example:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("Hello, my name is Ken\n");
    return 0;
}

Click Build and run. The console now shows:

Hello, my name is Ken

Tip: hold Ctrl and turn the mouse wheel to make the code larger or smaller. This works in many programs, including word processors.

Break it on purpose: press Run without building

Close the console window. Change the name again, so that the printf line reads printf("Hello, my name is Ryu\n");. This time click only Run (the green arrow), not Build.

Observe: the console still shows the old message:

Hello, my name is Ken

Your edit seems to have been ignored. Now click Build, then Run (or simply Build and run):

Hello, my name is Ryu

A second trap to try: leave the console window open, go back to the editor, and try to build again. The build buttons are greyed out. Code::Blocks will not rebuild a program that is still running. Close the console (press a key in it), and the buttons come back. If a console window ever refuses to close, you may need to end it, or Code::Blocks itself, from Task Manager.

What just happened

The text you type in main.c is source code. The computer cannot run it directly. When you click Build, Code::Blocks asks the GCC compiler to translate your source code into an intermediate object file (obj/Debug/main.o), and then to make a finished executable (bin/Debug/001-FirstCProgram.exe on Windows). Clicking Run simply starts whatever executable is already in that folder.

So when you edited the code and pressed only Run, you started the old executable, which was built before your change. The new source code had not been compiled yet. The habit to build: after every change, build again. Build often and test small changes one at a time. When something breaks, you will know exactly which change caused it.

This is the job of an integrated development environment (IDE). It puts an editor, a compiler, a build log, a way to run your program and (later in the series) a debugger together in one window.

No Code::Blocks right now? If GCC is installed, you can do the same two steps from a terminal. gcc main.c -o hello is the build step, and ./hello (or hello.exe on Windows) is the run step. Edit the file and run ./hello again without rebuilding, and you will see the old message, exactly like the experiment above.

Key terms

  • Project: a folder plus a Code::Blocks project file (.cbp) that keeps your source files and build settings together.
  • Source code: the human-readable C you type, saved in files ending in .c.
  • Compiler: the program (here, GCC) that translates source code into machine code.
  • Object file: the compiler’s intermediate output (.o), which is then turned into an executable.
  • Build: compile your source and produce an executable.
  • Executable: the finished program file the computer can run.
  • Run: start the most recently built executable. It does not rebuild.
  • IDE: an integrated development environment such as Code::Blocks.
  • Upper camel case (PascalCase): capitalising the first letter of every word, as in FirstCProgram.

Quick check

  1. You change your printf message and click Run, but the old message appears. Why, and what should you click instead?

    Show answer

    Run starts the executable that was last built, and your change has not been compiled yet. Click Build and then Run, or simply Build and run.

  2. Why might a project saved deep inside many nested folders cause problems?

    Show answer

    Very long file paths (over about 255 characters) can make tools fail, which shows up as confusing compile, debug or upload errors. Keep project paths short.

  3. The build buttons in Code::Blocks are greyed out. What is the most likely reason?

    Show answer

    Your program is still running in a console window. Close it, and the buttons become available again.

  4. What does “Process returned 0” tell you?

    Show answer

    The program reached return 0; in main and finished normally.

Optional: a recorded demonstration of these steps starts around 4:20. Creating the project begins at about 8:00, and building and running at about 15:30.

Part of the Introduction to C series. Next: printf, String Literals, and Escape Sequences