Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write a function that mimics the conversion that printf performs when it prints

ID: 2079854 • 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

The Implementation of the function in C is given below:


int* printDecimalDigits(int n) {
int y=0;
int remainder, reverse=0;
if(n<=0)
return -1;
else {
while(n>0) {
remainder=n%10;
reverse=reverse*10+remainder;
n=n/10;
y++; }
}
//Number has been reversed and the length is calculated
int a[y];
y=0;
while(reverse>0) {
a[y]=reverse%10;
reverse=reverse/10;
y++; }
//This prints the digits as required in the program
for(i=0;i<y;i++) {
printf("%d ",a[i]);
}
return a[];
} //End of function

Now if you pass n=1234 in the program it will give

1

2

3

4

at the output as required by you.