Sams Teach Yourself C in 21 Days

(singke) #1
Line 5 contains an additional comment explaining the variables that are being declared.
In line 7, an array of 13 elements is declared. In this program, only 12 elements are
needed, one for each month, but 13 have been declared. The forloop in lines 14 through
18 ignores element 0. This lets the program use elements 1 through 12 , which relate
directly to the 12 months. Going back to line 8, a variable,count, is declared and is used
throughout the program as a counter and an array index.
The program’s main()function begins on line 10. As stated earlier, this program uses a
forloop to print a message and accept a value for each of the 12 months. Notice that in
line 17, the scanf()function uses an array element. In line 7, the expensesarray was
declared as float,so%fis used. The address-of operator (&) also is placed before the
array element, just as if it were a regular type floatvariable and not an array element.
Lines 22 through 25 contain a second forloop that prints the values just entered. An
additional formatting command has been added to the printf()function so that the
expenses values print in a more orderly fashion. For now, know that %.2fprints a float-
ing number with two digits to the right of the decimal. Additional formatting commands
are covered in more detail on Day 14, “Working with the Screen, Printer, and Keyboard.”
DOuse arrays instead of creating several variables that store the same thing. For example, if

180 Day 8

you want to store total sales for each
month of the year, create an array with
12 elements to hold sales rather than
creating a sales variable for each month.
DON’Tforget that array subscripts start
at element 0.

Using

Multidimensional

DO DON’T


Arrays

A multidimensional array has more than one subscript. A two-dimensional array has two
subscripts, a three-dimensional array has three subscripts, and so on. There is no limit to
the number of dimensions a C array can have. (There isa limit on total array size, as dis-
cussed later in today’s lesson.)
For example, you might write a program that plays checkers. The checkerboard contains
64 squares arranged in eight rows and eight columns. Your program could represent the
board as a two-dimensional array, as follows:
int checker[8][8];

14 448201x-CH08 8/13/02 11:21 AM Page 180

Free download pdf