iGeekor - 1 year ago 65
C Question

# Explain code: positive integer conversion to other cardinal number, reverse order display

``````// Program to convert a positive interger 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;
}
while (numberToConvert != 0);
//display the result in the reverse order

printf(" Converted number = ");

for (--index;index >= 0; --index) {
nextDigit = convertedNumber[index];
printf ("%c", baseDigits[nextDigit]);
}

printf("\n");
return 0;
}
``````

I do not understand this code. How will it be able to show the reverse order? Especially the for statement inside the brackets. Why does
`--index`
appear twice? What's the meaning it and
`index >=0`
? What's the use of
`nextDigit`
?

``````for (--index;index >= 0; --index) {
nextDigit = convertedNumber[index];
printf ("%c", baseDigits[nextDigit]);
``````

Another new question:""
Why we also should output a number at least? and so here with the do loop?""

(Because using scanf to read long integer number of formatted input symbols is %ld. Because even if the user's input is 0 ,we also should output a number
at least, so here with the do loop)

Now analyse the code.

``````do {
convertedNumber[index] = numberToConvert % base;
++index;
numberToConvert = numberToConvert / base;
}
while (numberToConvert != 0);
``````

This code actually do the conversion and stores each digit of new base number as a different number in array.

Example: If input is 146 and you want to convert it to base 13 number, then

``````convertedNumber[0] = 3
convertedNumber[1] = 11
``````

At the end of the conversion thread exits from while loop and index value will be 2.

Now it comes to the for loop.

``````for (--index;index >= 0; --index) {
nextDigit = convertedNumber[index];
printf ("%c", baseDigits[nextDigit]);
}
``````

You need to print value at index 1 and index 0. So index value start with decrementing itself.

Please remember, the first statement in for loop is executed only once. So effectively, there is only one `--index;`per loop.

It finds the character to display for a given digit. Ex: for index[1]=10, it prints 'A' and index[0]=3, it prints '3'. So output is `A3`. This is done to do conversion from base 10 to any base from 2 to 16 (However, that check is not there! You need to add a check for user entered base and make sure it is [2, 16]).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download