Discussion
Which of the following statements are correct about the program?
#include <stdio.h>
char *fun(unsigned int num, int base);
int main()
{
char *s;
s=fun(128, 2);
s=fun(128, 16);
printf("%s\n",s);
return 0;
}
char *fun(unsigned int num, int base)
{
static char buff[33];
char *ptr = &buff[sizeof(buff)-1];
*ptr = '\0';
do
{
*--ptr = "0123456789abcdef"[num % base];
num /=base;
}while(num!=0);
return ptr;
}
Answer: A
Correct answer: It converts a number to a given base.
The function is a general base converter. It builds the string backwards from the end of the buffer, taking num % base as the next digit, looking that digit up in "0123456789abcdef", and dividing num by base until nothing remains.
Because both the digit table and the divisor come from the base parameter, it handles any base up to 16 - binary and hexadecimal are merely the two the caller happens to use. The do...while form guarantees at least one digit, so an input of zero yields "0" rather than an empty string.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development