Converting a decimal number to other number systems like binary, octal and hexadecimal is usually done separately. In the following program, it is enough to specify the decimal number and the radix or the base.
Algorithm
1. Read the decimal number and the base
2. Divide the number by base and get the remainder
3. Store the remainder in an array
4. Divide the number by base and set the quotient as the number
5. Repeat steps 2 to 4 till the number reaches zero
6. Display the contents of the array in reverse order
7. For hexadecimal check the array values before display
Algorithm
1. Read the decimal number and the base
2. Divide the number by base and get the remainder
3. Store the remainder in an array
4. Divide the number by base and set the quotient as the number
5. Repeat steps 2 to 4 till the number reaches zero
6. Display the contents of the array in reverse order
7. For hexadecimal check the array values before display
//Program for number system conversion
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
int n,radix,result[16],i=0,rem,num;
char c;
clrscr();
printf("Enter the decimal number\n");
scanf("%d",&n);
do
{
printf("\nEnter radix for conversion\n");
printf("2 --> Binary 8 --> Octal 16 --> Hexadecimal\n");
scanf("%d",&radix);
num=n;i=0;
while (n>0)
{
rem=n%radix;
result[i++]=rem;
n=n/radix;
}
n=num;
printf("The result\n");
for(i-=1;i>=0;i--)
{
if (radix==16)
{
switch (result[i])
{
case 10 : printf("A");
break;
case 11: printf("B");
break;
case 12 : printf("C");
break;
case 13 : printf("D");
break;
case 14 : printf("E");
break;
case 15 : printf("F");
break;
default : printf("%d",result[i]);
}
}
else
printf("%d",result[i]);
}
printf("\nWant to convert to other number system? Y(y) / N(n)\n");
c=getche();
}while (toupper(c)=='Y');
getch();
}
/*
OUTPUT
________
Enter the decimal number
208
Enter radix for conversion
2 --> Binary 8 --> Octal 16 --> Hexadecimal
2
The result
11010000
Want to convert to other number system? Y(y) / N(n)
y
Enter radix for conversion
2 --> Binary 8 --> Octal 16 --> Hexadecimal
8
The result
320
Want to convert to other number system? Y(y) / N(n)
y
Enter radix for conversion
2 --> Binary 8 --> Octal 16 --> Hexadecimal
16
The result
D0
Want to convert to other number system? Y(y) / N(n)
n
*/