Solution:
#include<stdio.h> // include stdio.h library
int main(void)
{
int num, choice,oct=0, base;
int bin = 0;
int i = 0, rem;
char hex_arr[50];
printf("Enter a number: ");
scanf("%d", &num);
while(1)
{
printf("Select conversion: \n\n");
printf("1. Decimal to binary. \n");
printf("2. Decimal to octal. \n");
printf("3. Decimal to hexadecimal. \n");
printf("4. Exit. \n");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
base = 2;
while(num != 0)
{
rem = num % 2; // get the remainder
bin = rem * (long long)pow(10, i++) + bin;
num /= 2; // get the quotient
}
printf("%lld", bin);
break;
case 2:
base = 8;
while(num != 0)
{
rem = num % 8; // get the last digit
oct = rem * (long long)pow(10, i++) + oct;
num /= 8; // get the quotient
}
printf("0o");
printf("%lld", oct);
break;
case 3:
base = 16;
while(num != 0)
{
rem = num % 16; // get the right most digit
if (rem < 10)
{
hex_arr[i++] = 48 + rem;
}
else
{
hex_arr[i++] = 55 + rem;
}
num /= 16; // get the quotient
}
printf("0x");
for(int j = i - 1; j >= 0 ; j--) // print the hex_arr in reverse order
{
printf("%c", hex_arr[j]);
}
break;
case 4:
printf("Exiting ...");
exit(1);
default:
printf("Invalid choice.\n\n");
continue;
}
}
}
0 Comments