Paweł Paweł - 2 months ago 12
C Question

Do-while loop - what's wrong with the terminating condition?

So I recently started learning from Steven Kochan's "Programming in C" book and I'm currently on chapter 8 - "Functions".
I have problem with exercise 8.16:
"Modify Program 8.14 so that the user can convert any number of integers. Make
provision for the program to terminate when a zero is typed in as the value of the
number to be converted."

The code for Program 8.14 is the following:

#include <stdio.h>
#include <stdlib.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;
}


My idea was initially to use a do-while loop around three functions in main functions like this:

do
{
getNumberAndBase();
convertNumber ();
displayConvertedNumber ();
}
while ( numberToConvert != 0);


but apparently it doesn't work. It's the last excercise in this chapter, I managed to do the rest but not for the world can I figure out what's wrong here.
Probably I'm just missing something obvious.

Answer

numberToConvert is already being used by convertNumber(), so let's not disturb that.

Put the whole block

getNumberAndBase();
convertNumber (); // Sets numberToConvert to zero before returning
displayConvertedNumber ();

inside a while(1) loop and put a check on the numberToConvert value in getNumberAndBase() function. Break out of the loop once you get the 0 value.

For sure, you can use another do...while loop, but somehow you need to make use of numberToConvert scanned value to meet the condition

"...Make provision for the program to terminate when a zero is typed in as the value of the number to be converted."

That said,

  • Always check for the return value of scanf() to ensure success.
  • Don't simply use globals, they can carry hidden troubles once the program starts going large. Define local variables and pass them (or pointer to them) around as long as possible.

Greater level of encapsulation is all we need. :)