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.

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