Programming in C

(Barry) #1
Character Arrays 109

The most notable point in the preceding program is the declaration of the character
array word.There is no mention of the number of elements in the array.The C language
allows you to define an array without specifying the number of elements. If this is done,
the size of the array is determined automatically based on the number of initialization
elements. Because Program 7.6 has six initial values listed for the array word, the C lan-
guage implicitly dimensions the array to six elements.
This approach works fine so long as you initialize every element in the array at the
point that the array is defined. If this is not to be the case, you must explicitly dimension
the array.
In the case of using index numbers in the initialization list, as in


float sample_data[] = { [0] = 1.0, [49] = 100.0, [99] = 200.0 };


the largest index number specified sets the size of the array. In this case,sample_datais
set to contain 100 elements, based on the largest index value of 99 that is specified.


Base Conversion Using Arrays


The next program further illustrates the use of integer and character arrays.The task is to
develop a program that converts a positive integer from its base 10 representation into its
equivalent representation in another base up to base 16. As inputs to the program, you
specify the number to be converted and also the base to which you want the number
converted.The program then converts the keyed-in number to the appropriate base and
displays the result.
The first step in developing such a program is to devise an algorithm to convert a
number from base 10 to another base. An algorithm to generate the digits of the con-
verted number can be informally stated as follows: A digit of the converted number is
obtained by taking the modulo of the number by the base.The number is then divided
by the base, with any fractional remainder discarded, and the process is repeated until the
number reaches zero.
The outlined procedure generates the digits of the converted number starting from
the rightmost digit. See how this works in the following example. Suppose you want to
convert the number 10 into base 2.Table 7.1 shows the steps that would be followed to
arrive at the result.


Ta ble 7.1 Converting an Integer from Base 10 to Base 2


Number Number Modulo 2 Number / 2
10 0 5
51 2
20 1
11 0

The result of converting 10 to base 2 is, therefore, seen to be 1010, reading the digits of
the “Number Modulo 2” column from the bottom to the top.

Free download pdf