C Program to Convert Decimal Number to Hexadecimal Number
C Program to Convert Decimal number into Hexadecimal :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include<stdio.h> #include<conio.h> #include<math.h> void dec_hex(long int num) // Function Definition { long int rem[50],i=0,length=0; while(num>0) { rem[i]=num%16; num=num/16; i++; length++; } printf("Hexadecimal number : "); for(i=length-1;i>=0;i--) { switch(rem[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("%ld",rem[i]); } } } //================================================ void main() { long int num; clrscr(); printf("Enter the decimal number : "); scanf("%ld",&num); dec_hex(num); // Calling function getch(); } |
Output :
1 2 | Enter the decimal number : 87274 Hexadecimal number : 154EA |
Logic of This Program :
In this program firstly we need to accept decimal number from the user using following statement -
1 2 | printf("Enter the decimal number : "); scanf("%ld",&num); |
Now after accepting the number we are calling the function which can evaluate equivalent hexadecimal number.
1 | dec_hex(num); // Calling function |
Inside the function we have declared 3 variables. Below table will explain the significance of each and every variable used inside the function.
Variable | Significance of the Variable |
---|---|
num | This variable is used to store the actual decimal number. We are dividing this variable for finding the remainder and quotient. |
rem[50] | It is remainder array which is used to store the reminder when we divide the number by 16. |
i | Used as subscript variable for remainder array i.e rem |
length | It is used to keep track of the size of a reminder array. |
Now perform below steps until the number becomes less than 0 -
- Divide the number with 16 and store reminder in an array
- Divide the number with 16 and store quotient in num variable
- Increment i and length
1 2 3 4 5 6 7 | while(num > 0) { rem[i] = num % 16; num = num / 16; i++; length++; } |
After coming out of the loop. We need to print reminder in reverse fashion. Now consider the following table in order to print array -
Remainder | Display this |
---|---|
10 | A |
11 | B |
12 | C |
13 | D |
14 | E |
15 | F |
In order to print reminders greater than 10 , refer above table. This can be done with switch case.
1 2 3 4 5 6 | case 10: printf("A"); break; case 11: printf("B"); break; |
Download Program :
[box]Download Code [/box]