write a function that mimics the conversion that printf performs when it prints
ID: 3793324 • Letter: W
Question
write a function that mimics the conversion that printf performs when it prints in decimal format. (use printf to print each digit.)
The function prototype is
int printDecimalDigits(int n);
If a number less than or equal to 0 is passed as input, The function should print nothing and return -1. Otherwise, it should print each decimal digit of n one a separate line starting from the most significant one. The function should then return 0. No leading zeros should be printed. Use a recursion to implement your function and write a unit test that adequately exercises it.
I still could not compile under gcc and it drive me crazy. please help. in c language.
Explanation / Answer
we will use putchar() library function.putchar() prints a character, we wil call putchar() for all digits.Using recursion we can print all digits one by one. putchar() prints a character,so to print digits using putchar(). We need to convert every digit to its corresponding ASCII value, We will do this by using ASCII value of ‘0’.
Following is complete C program.
int printDecimalDigits(int n){
if (n<=0)
{return -1; /* as mentioned in question*/
}
else{
if (n/10)
print(n/10);
/* It will Print the last digit */
putchar(n%10 + '0');
/*Since the digits should be printed left to right, the recursive call must appear before putchar() (The rightmost digit should be printed at the end, all other digits must be printed before it).*/
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.