Programming in C

(Barry) #1
Multidimensional Arrays 113

example, the character contained in baseDigits[10], or 'A', is displayed. And if the
val ue of nextDigitis 8 , the character '8'as contained in baseDigits[8]is displayed.
When the value of indexbecomes less than zero, the forloop is finished. At this
point, the program displays a newline character, and program execution is terminated.
Incidentally, you might be interested in knowing that you could have easily avoided
the intermediate step of assigning the value of convertedNumber[index]to nextDigit
by directly specifying this expression as the subscript of the baseDigitsarray in the
printfcall. In other words, the expression


baseDigits[ convertedNumber[index] ]


could have been supplied to the printfroutine with the same results achieved. Of
course, this expression is a bit more cryptic than the two equivalent expressions used by
the program.
It should be pointed out that the preceding program is a bit sloppy. No check was
ever made to ensure that the value of basewas between 2 and 16. If the user had
entered 0 for the value of the base, the division inside the doloop would have been a
division by zero.You should never allow this to happen. In addition, if the user had keyed
in 1 as the value of the base, the program would enter an infinite loop because the value
of numberToConvertwould never reach zero. If the user had entered a base value that
was greater than 16, you might have exceeded the bounds of the baseDigitsarray later
in the program.That’s another “gotcha” that you must avoid because the C system does
not check this condition for us.
In Chapter 8, “Working with Functions,” you rewrite this program and resolve these
issues. But now, it’s time to look at an interesting extension to the notion of an array.


Multidimensional Arrays


The types of arrays that you have been exposed to so far are all linear arrays—that is,
they all dealt with a single dimension.The C language allows arrays of any dimension to
be defined. In this section, you take a look at two-dimensional arrays.
One of the most natural applications for a two-dimensional array arises in the case of
a matrix. Consider the 4 x 5 matrix shown in Table 7.2.


Ta ble 7.2 A 4 x 5 Matrix


10 5 -3 17 82
9 008-7
32 20 1 0 14
0 0876

In mathematics, it is quite common to refer to an element of a matrix by use of a
doublesubscript. So if you call the preceding matrix M,the notation Mi,jrefers to the
element in the ith row,jth column, where iranges from 1 to 4, and jranges from 1 to 5.

Free download pdf