Click here to Skip to main content
14,218,548 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hello,

I'm new in the field. Unfortunately I don't understand the third function in this program I want to know what do
for(--digit; digit >= 0; --digit )

and
baseDigits[nextDigit]
.

Thank you.

What I have tried:

#include <stdio.h>
int convertedNumber[64];
long int numberToConvert;
int base;
int digit = 0;
void getNumberAndBase (void)

{
        printf ("Number to be converted? ");
        scanf ("%li", &numberToConvert); printf ("Base? "); scanf ("%i", &base);
        if ( base < 2 || base > 16 ) {
          printf ("Bad base - must be between 2 and 16\n"); base = 10; }
}
void convertNumber (void) {
        do { convertedNumber[digit] = numberToConvert % base;
             ++digit;
             numberToConvert /= base;
           }
              while ( numberToConvert != 0 );


}
void displayConvertedNumber (void) {
        const char baseDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int nextDigit;
        printf ("Converted number = ");
        for (--digit; digit >= 0; --digit )
        {
          nextDigit = convertedNumber[digit];


          printf ("%c", baseDigits[nextDigit]);
        }
        printf ("\n");

}
int main (void) {
        void getNumberAndBase (void), convertNumber (void), displayConvertedNumber (void);
        getNumberAndBase ();
        convertNumber ();
        displayConvertedNumber ();
        return 0;
}
Posted
Updated 13-Apr-18 19:51pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

A for statement has four parts:
for (a ; b ; c )
   d;
Where:
a is executed before the loop starts
c is executed after the loop has run
b is tested after c has executed
d is executed each time the loop runs.
In pseudo code it looks like this:

1) Execute a
2) If ( not b ) goto (3)
2.1) Execute d
2.2) Execute c
2.3) Goto (2)
3) done.

So in your case:

1) Subtract one from digit
2) if ( digit < 0 ) exit the loop.
2.1) Execute these lines:
nextDigit = convertedNumber[digit];
printf ("%c", baseDigits[nextDigit]);
2.2) Subtract one from digit
2.3) Loop round to (2) and check again.

The other code fragment is simple: baseDigits is an array, and your code
baseDigits[nextDigit]
extracts the element at the position given by the index value in nextDigit - so if the index is zero, it fetches the first character '0', if it's one it fetches '1', and so on up to fourteen 'E' and fifteen 'F'


You wrote this code for your homework, so you should really understand what it does...
   
Comments
steve NN 14-Apr-18 22:22pm
   
thank you
OriginalGriff 15-Apr-18 1:59am
   
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100