In: Computer Science
PLEASE NOTE:1)-DO NOT USE FUNCTIONS USE ONLY DO WHILE LOOP.
2)DO NOT USE IN-BUILT FUNCTIONS.
3)Use of string and char is not allowed.
Write a program in c laungage that prints a table of the binary, octal and hexadecimal equivalents of the decimal numbers in the range1 through 256.
Here is the code that will print table of number, binary equivalent of number, octal equivalent of number and hexa decimal equivalent of number using a do while loop:
/**********************************************************
Program to convert a decimal number to binary,
octal and hexadecimal using recursion for numbers 1-256
**********************************************************/
#include<stdio.h> // include stdio.h library
//Method declaration
void convertToBaseX(int, int);
//main method
int main(void) {
//Number variable to keep 1st number
int num = 1;
//Printing table header
printf("number\t\t\tBinary\t\tOctal\t\tHexadecimal\n");
//Do while loop
do {
//print number in first column
printf("%d", num);
printf("\t\t\t");
//calculate binary and print the result for table
convertToBaseX(num, 2);
if (num > 7 && num <= 127) {
printf("\t\t");
} else if (num > 127) {
printf("\t");
} else {
printf("\t\t");
}
//calculate octal and print the result for table
convertToBaseX(num, 8);
if (num > 7 && num <= 127) {
printf("\t\t\t");
} else if (num > 127) {
printf("\t\t\t");
} else {
printf("\t\t\t");
}
//calculate hexadecimal and print the result for table
convertToBaseX(num, 16);
//new line for next row
printf("\n");
//increment the number
num++;
} while (num <= 256); //while loop will run till number is 256
return 0; // return 0 to operating system
}
/**
* Method to print in requried base
* @param num: number to convert
* @param base: base in which number is requried to be converted
*/
void convertToBaseX(int num, int base) {
//remainder handling variable
int rem;
//if number is zero then no conversion
if (num == 0) {
return;
}
//other wise convert the number to requried base
else {
//divide number by base and get the remainder
//to find rightmost digit
rem = num % base;
convertToBaseX(num / base, base); // recursive call
//handle base 16
if (base == 16 && rem >= 10) {
printf("%c", rem + 55);
} else {
printf("%d", rem);
}
}
}
Output:
Screen shot of output table (Output is very large so broken into different images):