Uh-oh, it looks like your Internet Explorer is out of date.

For a better shopping experience, please upgrade now.

C For Dummies

C For Dummies

2.0 2
by Dan Gookin

See All Formats & Editions

Come "C" what all the excitement's about! C programs are fast, concise, and versatile, and you'll be writing them in no time. This friendly book unlocks the mysteries of coding, compiling, adding comments, and using keywords, I/O, variables, integers, and all the rest. You'll write your first C program before you finish Chapter 1!


Come "C" what all the excitement's about! C programs are fast, concise, and versatile, and you'll be writing them in no time. This friendly book unlocks the mysteries of coding, compiling, adding comments, and using keywords, I/O, variables, integers, and all the rest. You'll write your first C program before you finish Chapter 1!

Product Details

Publication date:
For Dummies Series
Edition description:
Older Edition
Product dimensions:
7.41(w) x 9.24(h) x 1.18(d)

Read an Excerpt

Lesson 9-1: Asking for Arrays

Array is one of those words that loses its meaning the more you say it. Array. A ray. Air ray. Hairy. Hooray!

An array is nothing more than an organized collection of stuff. Suppose that you're decorating cookies, and, because you're obsessively neat, you have arranged them into two lines: one ready for decorating and another already decorated. Nerdy folk would say that you have two arrays of cookies. C programmers would say that you have an initialized array (decorated cookies) and an uninitialized array (undecorated cookies). Me? I would just eat the cookies and suck the raw frosting from the decorating tube.

What does all this mean? Nothing more than identifying a collection of stuff with the word array.

  • An array is a collection of stuff, like a row of cookies or a list of items in a column or a line of cars backed up seven miles on the freeway.
  • You can cheerfully ignore the terms initialized and uninitialized for now.
  • Arrays open up the heretofore unexplored region of database programming in C. Because an array is essentially a collection of stuff in a database, you can do databasey things with arrays: List them, sort them, unsort them, create bogus databases for the IRS, and so on.
  • It's the database manipulation that makes arrays so handy.

The whole deal with arrays

In the C language, an array is a collection of variables, all of the same type. You can have an array of integers, single-character variables, floats, doubles, and so on.

Alas, you can't have an array of strings -- not yet, anyway. You have enough to do with integer arrays to keep you busy for this lesson.

Suppose that a bunch of football jocks are standing in line at the school café. Since you're standing behind them, they'll probably hoard all the good food before you get there. But that's not the point. What you should notice instead are the numbers printed across the back of their jerseys.

Unbeknownst to the football players, integers are printed on their jerseys. (They know that they have numbers on their jerseys, but not all of them know that the numbers are integers.) Standing there, they make up, in a way, an integer array, which you could write like this:

16, 88, 45, 99, 6, 33


You could also make an array from their names -- a string array:

Sherman, Fernan, Hastings, Harrison, Best, Hayden

Then you could make an array from the first letter of their girlfriend's names:

S, E, K, K, K, K

(Kelly is very popular.)

Each of these three examples is an array. The examples are a collection of items all of the same type: integers, strings, and characters.

Now for the nerdy terms:

Element: Each item in an array is called an element. The array can have as many elements as it needs (although in your computer the true size is limited by how much memory your PC has). In the preceding example, each of the arrays contains six elements: six jersey numbers, six names, six girlfriend's initials.

(Yes, even though Kelly appears four times in the last array, the K still counts as four elements. Not all the elements in an array have to be different.)

Here's something weird:

Zero: The first element in an array is numbered zero. Normally, if C were the least bit normal, the first element would be one. After all, all humans begin counting things as "One, two, three. . . ." Because C has to be different, though, the first element is zero.

  • C says, "Zero, one, two. . . ." Get used to it.
  • Please don't run away screaming just yet.
  • Arrays contain all the same type of variable: all integers, all characters, all floats -- all the same.
  • Each item in an array is an element.
  • Not every element has to be different. You can have an array of 52 items that are all the number 12, and it's still an array.
  • The first item in an array is number zero. This requirement is very weird and will toss you for a loop more than once during your C programming career.
  • Quite a few things in your PC begin numbering at zero. For example, the first memory address in your computer is address zero (written as 0x00000). The first argument typed at the DOS prompt is referred to as argv[0], which is also an array, as described in Lesson 6-3 in C For Dummies®, Volume I. Also gander at the PRINTME1.C program in Lesson 8-4. See how the first printer port in your PC (called LPT1) is really zero, or 0x00? LPT2, the second printer port, is value 0x01. See? I'm not making this stuff up either.

The element zero deal (which you don't have to read)

This element zero thing can drive you nuts, but don't let it. For example, the first jock in line has 16 on his jersey. That's element zero of the array. Here's how you could type that up in a nerdy C language-like way, assuming that the array is named jock_array and the element numbers are in square brackets:

jock_array[0] = 16;

jock_array[1] = 88;

jock_array[2] = 45;

jock_array[3] = 99;

jock_array[4] = 6;

jock_array[5] = 33;

Although this stuff may look complex, it's just a way to write down how each of the jock's jersey numbers would fit into an array. The zeroth (yes, that's a real word) element is 16; then 88, 45, 99, and 6; finally, the fifth element is 33. Though 33 is the sixth item in the array, in weirdo C it's referenced as item 5.

A simple program before you get too bored

An array can hold any series of numbers, such as the numbers in a safe's combination. The following program, SAFE.C, is the same program the manager at my local bank uses to remind herself how to open the Big Safe. (I'm reprinting this program with her permission; as long as you don't know that it's the Bank of America on First Street, she said that it would be okay.)

Carefully type this source code into your editor. The integer array, which is discussed in the following sections, is the only new item in there. For now, just type carefully, and you'll be okay:

Name: SAFE.C

#include <stdio.h>

void main()

    int numbers[] = { 36, 24, 12 };

    printf("The combination for the safe: ");
    printf("1. Turn to %i left. ",numbers[0]);
    printf("2. Turn to %i right. ",numbers[1]);
    printf("3. Turn to %i left, open. ",numbers[2]);


Compile and run. Here's what you should see:

The combination for the safe:
1. Turn to 36 left.
2. Turn to 24 right.
3. Turn to 12 left, open.

The array stored the three numbers, and then various printf statements reached into the array to grab the numbers back out.

  • Like any other variable, an array must be declared before you can use it. This subject is covered in the very next section.
  • Arrays are declared with the same words as any other variable: int for integer arrays, float for floating-point number arrays, and so on.
  • Square brackets are big in Array Land.
  • Elements in an array are referred to by the array name and then the element number. This subject is covered later in this lesson, in the section "Referring to elements in an array."

Properly declaring arrays in C

Like everything else in C, you can't pluck an array from thin air. No, as with other types of variables, you must declare it and type it in a proper and cryptic manner along with any other variables you plan to use in your program.

An array in C can be declared in two ways, depending on whether the array is empty or full.

A full array is one that already has information in it, like the numbers array in the SAFE.C program. It's defined like this:

int jock_array[] = {16, 88, 45, 99, 6, 33};

Table 9-1 tells you how each item fits into the big picture. Basically, there are three things: the type of array, int (integer); the array name, jock_array; and the values assigned to that array. The whole thing ends with a semicolon, just as any variable declaration does.

Table 9-1 Items You Need for a Full (Initialized) Array


What It Does


Defines it as an array of integers


The name of the array (square brackets are required and should be empty); the compiler figures out the array's size for you


Says "Set the contents of the array equal to the following values"


Curly brackets contain the array's info

16, 88, 45, 99, 6, 33

Numbers, separated by commas, to put into the array


Final curly bracket


Semicolon at the end of the variable declaration

The other type of array in C is empty, one you create to be filled in later. It's defined this way:

float coworker_IQ[20];

Rather than have numbers or other data assigned to this array, it merely has a size specified; 20 elements, in this example. It means that the coworker_IQ array has room for as many as 20 floating-point numbers.

The following check marks should answer most of the questions buzzing around in your head right now:

  • In both cases, the array is declared similarly to any other variable. First comes the variable type and then the variable name. The first array in the preceding example is an integer array named jock_array. The second array is a float array named coworker_IQ.
  • A full array is also referred to as an initialized array. It means that all the data -- each element in the array -- is already there.
  • An empty array is referred to as an uninitialized array.
  • For an initialized array, the values in the array are listed when the array is defined -- just as you can define any variable with a preset value, as explained in Lesson 3-3 in Volume I. Each element appears in curly brackets separated by a comma.
  • Love them curly brackets.
  • Commas appear after each number in the array, except for the last one. You will forget this statement often, and the compiler may or may not warn you, but your program will definitely screw up.
  • The last item in the array does not have a comma by it.
  • As always, a variable declaration must end in a semicolon, no matter which type of array you define.
  • For an uninitialized (or empty) array, you simply state how many elements you want in the square brackets. In the preceding example, the number of elements in the coworker_IQ array is set equal to 20; that array can have as many as 20 elements in it.
  • Technically speaking, when you declare an array like this:
  • int chairs[12];

    you're telling the compiler to set aside space for an array that contains 12 elements of integer number size. It's the same as though you were throwing a dinner party and invited 12 people -- you would need a long table with 12 chairs. (And then pray that no more than 12 people show up and each of them needs only one chair on which to sit.)

  • No, you cannot readily change an array's size; you must set the value when you write the program and hope that you set it big enough. This challenge is something C programmers wrestle with every day.
  • The square brackets are empty when you declare an initialized array. Fortunately, the compiler is smart enough to figure out the array's size and set it for you automatically. In the following declaration:
  • char cards[] = {'A', 'J', 'Q', 'K'};

    the compiler creates a single-character array named cards that can hold four elements. Then the characters A, J, Q, and K are stuffed into the array.

Referring to elements in an array

Each element in an array is its own variable. It has to be. Otherwise, you would never be able to pluck out any individual item in the array, and then, well, what would be the point?

To refer to any item in an array, you have to know the array's name and the element's number. The array's name is like any other variable name in C. The element number, however, is weird because the first element is zero, not one. When you know those two things, you just write down the array name, stick the element number between the square brackets, and -- presto! -- you have a variable just like any other.

In the SAFE.C program, for example, the first item in the array is referred to as numbers[0]. Even though a funky square bracket is in there, the compiler sees the thing as a single integer variable.

  • You can use array items throughout your program just as you would use any variable.
  • Assign a value to an array element just as you would assign any variable:

    orbit[1] = 53.449;


    election[2000] = 78123;


    input[7] = getch();

  • Even the element number can be a variable:

    loop[x] = counter();

    Here, variable x is used to indicate an element in the loop array, an element that has the value returned by the counter function.

Sticking stuff into an array (initializing it)

Here's a truly meaningless program for you. It creates an empty (uninitialized) array that can hold 20 elements (numbered 0 through 19, natch). Then the program fills those elements with the numbers 1 through 20, then 20 through 1, and then random numbers.

Carefully type this program into your editor. It uses the random-number-generation routines from the program RANDOM4.C in Lesson 5-7 in Volume I. You can cut and paste that chunk of text (the rnd and seedrnd functions). Although the source code seems rather long, it's really the same for loop repeated three times. Cut and paste!


#include <stdio.h>
#include <stdlib.h>
#include <time.h> //for seeding randomizer

#define ELEMENTS 20

int rnd(int range);
void seedrnd(void);

void main()

int blorf[ELEMENTS];
int x;

/* First pass, fill array with values 1 through 20 */

printf("Initialize array from 1 to 20: ");
blorf[x] = x+1;

/* Second pass, fill array with values 20 through 1 */

printf(" And now from 20 to 1: ");
blorf[x] = 20-x;

/* Final pass, fill array with random values */

printf(" And now random numbers: ");
blorf[x] = rnd(20)+1;

int rnd(int range)

int r;
r=rand()%range; //spit up random number

void seedrnd(void)


Double-check your work. An error is bound to be in there somewhere -- a missing semicolon or comment character.

Compile and run.

Here's the result:

Initialize array from 1 to 20:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
And now from 20 to 1:
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
And now random numbers:
7 11 3 11 17 18 16 16 9 7 5 19 12 20 13 1 13 2 4 8

Soothing words for the harried HURRAY.C program

Like most long programs, the HURRAY.C program contains a great deal of repetition. The idea is to fill the array and then display the results. Normally, your program might fill an array only once, either by itself or with user input. The array's contents may change, but probably not as shown in HURRAY.C.

The stdlib.h and time.h header files are included for the rnd and seedrnd functions, which are covered in Lesson 5-7 in Volume I. Notice that those functions are properly prototyped; refer to Lesson 5-1.

The define directive is used to set the size of the array, by assigning the shortcut word ELEMENTS to that value:

#define ELEMENTS 20

This shortcut is used throughout the program to represent the array's size. Oh, you could use the value directly, but by using the define directive, you can globally change the array size without having to go out and hunt down those references in the program's every nook and cranny.

The following line creates an array of integers named blorf (the array is named "blorf," not the integers). The array can hold 20 elements, as indicated by the ELEMENTS shortcut word:

int blorf[ELEMENTS];

The for loop repeats 20 times, raising the value of variable x from 0 to 19, which just also happens to be the way the elements are numbered in the array:


(See? Element zero does come in handy.)

Element x in the array is given the value of variable x plus one:

blorf[x] = x+1;

If x equals 0 (as it would the first time through the for loop), for example, element 0 of the array equals the value 1. Notice that the value of x is not incremented here. Incrementing x happens in the for loop. To display values 1 through 20, you must add 1 to the value of x. (Incrementing x is written as either x = x + 1 or x++.)

The printf statement displays element x's value for the blorf array:


The value is displayed followed by the space character, \x20. Again, I do this because "%i " printed in a book doesn't make it clear whether a space follows the little i.

The second for loop reinitializes the array almost identically to the first for loop. The exception is the value assigned; it's 20-x, which puts values 20 through 1 into the array (the variable x loops from 0 through 19; 20 minus 0 is 1; 20 minus 1 is 19; and so on):

blorf[x] = 20-x;

In the final for loop, random values from 1 through 20 are stuffed into the blorf array:

blorf[x] = rnd(20)+1;

Again, refer to Lesson 5-7 for details about the rnd(20)+1 construction.

The array named blorf is filled with three different sets of numbers, each of which can be changed like any other variable. See the previous sidebar, "Soothing words for the harried HURRAY.C program," for more detailed information about what's going on.

  • Values can also be placed into an array by reading the information from the keyboard. You can use the scanf or gets functions for that; refer to Lesson 3-1 in Volume I for information about reading numerical values from the keyboard.
  • Use gets to read information from the keyboard. More and more, I'm growing to hate the scanf function.
  • Keep in mind that values read in from the keyboard must match the type of variable the array holds: ints for integer arrays, floats for floating-point arrays, and so on.
  • The #define directive in this program sets the size of the blorf array to 20 elements. That's done so that the array size can be adjusted easily by editing that one line. Refer to Lesson 3-4 in Volume I for information about how handy the #define directive can be.
  • The \x20 escape sequence in the various printf statements inserts a blank (a space) between the array numbers. Refer to Table 2-1 in Volume I for more information about escape sequences.

An old but useful chestnut

The following program is a lottery-number picker, which is listed at the end of Volume I. Now that you're familiarizing yourself with arrays, the program should make a little more sense to you. It's listed next, minus the extensive comments from Volume I so that you can peruse the array aspects of the program:


#include <stdio.h>
#include <stdlib.h>
#include <time.h> //for the seedrnd() function

#define RANGE 50 //number of numbers
#define BALLS 6 //number of balls to draw
#define DELAY 1000000 //delay interval between picks

int rnd(int range);
void seedrnd(void);

void main()

int numbers[RANGE]; //array that holds the balls
int i,b;
unsigned long d; //delay variable
printf("L O T T O P I C K E R ");
seedrnd(); //seed the randomizer

/* initialize the array */

for(i=0;i<RANGE;i++) //initialize the array
printf("Press Enter to pick this week's numbers:");

/* draw the numbers */

printf(" Here they come: ");
for(d=0;d<=DELAY;d++); //pause here
/* picks a random number and check to see whether it's already been picked */
b=rnd(RANGE); //draw number
while(numbers[b]); //already drawn?
numbers[b]=1; //mark it as drawn
printf("%i ",b+1); //add one for zero
printf(" Good luck in the drawing! ");

/* Generate a random value */

int rnd(int range)

int r;
r=rand()%range; //spit up random number

/* Seed the randomizer */

void seedrnd(void)


Enter this source code into your editor (if you haven't already done so from Volume I). Compile and run.


Press Enter to pick this week's numbers:

Press the Enter key.

Here they come: 35 11 49 34 26 37

Good luck in the drawing!

The program picks six numbers from 1 to 50 as your lucky lotto numbers this week. (You can change the range of numbers by entering a new value for the RANGE define, and you can choose more or fewer numbers by changing the BALLS define, both at the beginning of the source code.)

This lotto program works the same way any computer card game works. Like cards in a deck, balls in a lottery machine can be drawn only once. The object is not to generate the same random number twice. That is, you can't draw the same lotto ball, bingo ball, or card from a deck in the real world, so you shouldn't be able to do that in a computer program either.

The solution is to keep track of the numbers (cards or whatever) drawn by using an array. The array is initialized with all zeros to start, which is done in Lines 23 and 24 in LOTTO.C:

for(i=0;i<RANGE;i++) //initialize the array


Then, as the random numbers are drawn, a one is inserted into the array to indicate which numbers (cards, whatever) have already been used. The following snippet makes that happen:

b=rnd(RANGE); //draw number
while(numbers[b]); //already drawn?

numbers[b]=1; //mark it as drawn
printf("%i ",b+1); //add one for zero

The variable b holds the number drawn, using the rnd() function introduced in Lesson 5-7 in Volume I. The rnd() function returns a value representing an element in the array. The do-while loop checks to see whether that value is equal to one -- which is TRUE -- if so, it keeps looping, generating new random numbers and checking the array for a zero or a one.

If the random number returned hasn't yet been drawn, the program continues; first, the value one (TRUE) is placed into the array with the numbers[b]=1; statement. That marks that number as "used." Then the number drawn is displayed on-screen. Note that the number displayed is b+1. That's because the rnd() function returns a value from zero through "RANGE." That's okay for filling the array, which also begins at element zero, but normally there's no zero ball in a lottery game.

The loop continues until the number of balls (represented by the shortcut word BALLS) has been drawn.

  • All this nonsense is created to ensure that the same number isn't drawn twice. By sticking a 1 into the array, you ensure that that number isn't drawn again in your program.
  • You could modify the LOTTO.C program to draw all 50 balls; just change the value of BALLS to 50 in the define statement. Notice that the program takes longer and longer to display the last few numbers as it waits for the random-number generator to produce a number that hasn't yet been drawn.
  • Now you can write that card game! You need an array of 52 elements, each of which represents a card in the deck. You can use a do-while loop similar to the one in LOTTO.C to determine which cards have already been drawn.
  • I could have initialized the array with values other than zero, and I could have used a value other than one to show that a ball had been drawn. In C, however, the values zero and one are typically used to represent FALSE and TRUE conditions, respectively. For more info, refer to Lessons 7-2 and 7-3 in Volume I.
  • I've been called on this before. The value 1 is not really equal to TRUE in C. Any nonzero value could be taken to equal 1. This is a minor quibble, raised primarily by minor quibblers.

Lesson 9-1 Quiz

1. The first element in an array is
A. The best element.
B. Element numero uno.
C. Element number one.
D. The zeroth element.

2. Zeroth is a real word:

3. What can be said about the following? int high_scores[] = { 99, 98, 99, 97};
A. It's an integer array.
B. The array has four elements.
C. The array is named high_scores.
D. Patrice Dabrowski was absent, so there is no 100 score.
E. All of the above.

4. Which of the following statements defines a floating-point array that contains three elements?
A. float ice_cream[3];
B. float buoy[] = {1.0794, 33.0, 1678.5};
C. float point[3] = { 1, 2, 3};
D. float root_beer[2];

5. What was the name of Paul Bunyan's ox?
A. Blue.
B. Babe.
C. Big Ox.
D. Bovus.

Meet the Author

Dan Gookin (Coeur d'Alene, Idaho) wrote the first-ever For Dummies book, DOS For Dummies, as well as the bestselling PCs For Dummies and Word For Dummies. He wrote C For Dummies Volumes One and Two. Dan's books have been translated into 32 languages and have more than 11 million copies in print.

Customer Reviews

Average Review:

Post to your social network


Most Helpful Customer Reviews

See all customer reviews

C for Dummies 3.7 out of 5 based on 0 ratings. 6 reviews.
Anonymous More than 1 year ago
Guest More than 1 year ago
It's a good starting out book on C,but the lessons don't compile in linux.
Guest More than 1 year ago
C For Dummies Volume 1&2 is a great way for a beginner to learn the basics, concepts, and syntax of C. While I was reading this I often times switched between 'The C Programming Language' and this book, and this book is so much clearer then K&R2. This book by no means will make you expert in C, your very far from that after readin this. It will however give you the understanding of the concepts, basics, and syntax, much sooner. I recomend reading 'The C Programming Language' after reading this, as you will no doubtly get the context much easier after this. I also recomend 'The C Programming Language' it because of the standard library and refrence manual in the back. These two books will make you ready to take on some larger projects, and possibly pick up some intermediate C programming books. The downside of this book: Many concepts taught are frowned on my expirience C programmers. Many concepts are also left out. I think this book is best to build a basic knowledge, then you can read 'The C Programming Language.' Truly those two books couple together are a great read. I'm hoping that Dan Gookin makes a 3rd volume, possible with the missing chapter and supplmental lessons included.
Guest More than 1 year ago
The book is great if you know pretty much nothing about the 'C' language. Dan Gookin does ramble on a lot, and the end-of-the-lesson quiz as well as end-of-the-chapter final exam will certainly keep you on your toes. Recommended for newbies. It is kind of boring but in the end, it does what is supposed to.
Guest More than 1 year ago
I think that this was one of the best books that I have ever read on programming languages. I think that if you want to learn C, you should first learn a little bit of any basic language.
Guest More than 1 year ago
C For Dummies volume one and two helped me learn and master the C language more quickly than any other book about programming languages I have ever read. I reccomend it to anyone. :)