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)

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