Programming in C

(Barry) #1

110 Chapter 7 Working with Arrays


To write a program that performs the preceding conversion process, you must take a
couple of things into account. First, the fact that the algorithm generates the digits of the
converted number in reverse order is not very nice.You certainly can’t expect the user to
read the result from right to left, or from the bottom of the page upward.Therefore, you
must correct this problem. Rather than simply displaying each digit as it is generated,
you can have the program store each digit inside an array.Then, when you’ve finished
converting the number, you can display the contents of the array in the correct order.
Second, you must realize that you specified for the program to handle conversion of
numbers into bases up to 16.This means that any digits of the converted number that
are between 10 and 15 must be displayed using the corresponding letters, A through F.
This is where our character array enters the picture.
Examine Program 7.7 to see how these two issues are handled.This program also
introduces the type qualifier const,which is used for variables whose value does not
change in a program.

Program 7.7 Converting a Positive Integer to Another Base
// Program to convert a positive integer to another base

#include <stdio.h>

int main (void)
{
const char baseDigits[16] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int convertedNumber[64];
long int numberToConvert;
int nextDigit, base, index = 0;

// get the number and the base

printf ("Number to be converted? ");
scanf ("%ld", &numberToConvert);
printf ("Base? ");
scanf ("%i", &base);

// convert to the indicated base

do {
convertedNumber[index] = numberToConvert % base;
++index;
numberToConvert = numberToConvert / base;
Free download pdf