C language Now that we know loops, we can write a function that converts a numbe
ID: 3793971 • Letter: C
Question
C language
Now that we know loops, we can write a function that converts a number’s representation between two bases. Numbers are internally represented in base 2, but when you print an integer x with printf("%d ", x); you get the decimal representation of the number. For this problem, you write a function that mimics the conversion that printf performs when it prints in decimal format. (You still 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 least significant one (units first, followed by tens, and so on). The function should then return 0. No leading zeros should be printed. Use a while loop to implement your function and write a unit test that adequately exercises it.
B. Continuing Problem A, now write a function that prints the decimal digits of its argument starting from the most significant one. Keep the same interface and unit test as in Problem A. Use recursion to solve this problem. Note how recursion allows you to print the digits in reverse order of computation. If we want to use a loop instead of recursion, we need to wait until Chapter 3 to achieve the same result.
Explanation / Answer
#include <stdio.h>
int i = 0;
int arr[10];
int printDecimalDigits(int n)
{
if(n <= 0)
{
return -1 ;
}
else
{
while(n > 0)
{
printf("%d ",n%10);
n = n/10;
}
return(0);
}
}
int printDecimalDigitsMSB(int n)
{
if(n <= 0)
{
for(i=i-1;i>=0;i--)
{
printf("%d ",arr[i]);
}
return 0 ;
}
else
{
arr[i] = n%10;
i++;
n = n/10;
printDecimalDigitsMSB(n) ;
}
}
int main()
{
int n;
printf("Enter the integer number ");
scanf("%d",&n);
printDecimalDigits(n) ;
printDecimalDigitsMSB(n) ;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.