Vipasana Vipasana - 3 months ago 8
C Question

From integer to char array of digits and printing

I have an integer in c language and I want to create a char array and insert the last digit each time using modulu 10. after that I need to print the array from end to beggining in order to get the number printed in the right order. I know it sounds wierd, but I need to do it exactly like this.
But something is not working. the array is created fine, but than the char printing isn't working. this is what I did:

int baseChange (int base, int newBase, int num)
{
int baseTen = toBaseTen(base, num); //give me a number on base 10
char finalBase[24];
int i;
for (i = 0; baseTen != 0; i++)
{
int remain = baseTen % newBase;
finalBase[i] = (char)(remain); //insert the last digit to the array
baseTen /= newBase;
}
// Print finalBase from end to beginning in order to get the final number in the correct order:
for (i--; i >= 0; i--)
{
printf("i is: %d... %c", i, finalBase[i]);
}
return SUCCESS_EXIT;


}

If I print finalBase[i] during the first for loop, I get the right numbers, But after that, the second for loop is not printing anything. Why?
Please help.
Thanks a lot!

Answer

You are type casting Integer to Character, So it will consider your int as a ASCII value of some character. And It will add that character to your array instead of your number. So try following:

int baseChange (int base, int newBase, int num)
{
int baseTen = toBaseTen(base, num); //give me a number on base 10
char finalBase[24];
int i;
for (i = 0; baseTen != 0; i++)
{
    int remain = baseTen % newBase;
    finalBase[i] = (char)(remain+48); //insert the last digit to the array
    baseTen /= newBase;
}
// Print finalBase from end to beginning in order to get the final number in the correct order:
for (i--; i >= 0; i--)
{
    printf("i is: %d... %c", i, finalBase[i]);
}
return SUCCESS_EXIT;
}

I've changed finalBase[i] = (char)(remain); to finalBase[i] = (char)(remain+48);.

Because numerics in ASCII starts with 48 so add 48 to every number you get in the loop, so that it can be converted to 0-9. Thats it!

Second loop is not Printing anything WHY ?.

Because ASCII from 0-9 is not printable or are spaces and tabs.

Hope this will help you!

Comments