In this blog i will be writing all crap code for the questions asked in various interviews.Starting with the following question.
How to convert a decimal number to its equivalent Hexa-decimal equivalent. Give a C/C++ code for the same.
Explanation and Algorithm :
If you don't know or Forgotten what is Decimal/Hex-Decimal Numbers, the following table will tell u that.
HEXADECIMAL | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
DECIMAL | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
Steps:
- Divide the decimal number by 16. Treat the division as an integer division.
- Write down the remainder (in hexadecimal).
- Divide the result again by 16. Treat the division as an integer division.
- Repeat step 2 and 3 until result is 0.
- The hex value is the digit sequence of the remainders from the last to first.
DIVISION | RESULT | REMAINDER (in HEX) |
188 / 16 | 11 | C (12 decimal) |
11 / 16 | 0 | B (11 decimal) |
ANSWER | BC |
C++ Code:
#include <iostream>C Code:
using namespace std;
int main(){
int iDecimalNumber;
cout<<"Enter a decimal number to convert it to Hex :";
cin>>iDecimalNumber;
cout<<"Its Hex Equivalent is: "<<hex<<iDecimalNumber<<endl;
}
#include "stdio.h"Simple isn't it :P. you didn't like it ??.
int main(){
int iDecimalNumber;
printf("Enter a decimal number to convert it to Hex :");
scanf("%d",&iDecimalNumber);
printf("Equivalent Hexa-Decimal Number is :");
printf("%X\n",iDecimalNumber);
}
You can go around the globe. Think smart :D.
No comments:
Post a Comment