I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.
#include <iostream> #include <math.h> using namespace std; //Function declaration long long convertDecimalToBinary(int); int main() { int n, binaryNumber; cout << "Enter a decimal number: "; cin >> n; binaryNumber = convertDecimalToBinary(n); cout << n << " in decimal = " << binaryNumber << " in binary" << endl ; return 0; } long long convertDecimalToBinary(int n) { long long binaryNumber = 0; int remainder, i = 1, step = 1; while (n!=0) { remainder = n%2; cout << "Step " << step++ << ": " << n << "/2, Remainder = " << remainder << ", Quotient = " << n/2 << endl; n /= 2; binaryNumber += remainder*i; i *= 10; } return binaryNumber; }
Result:
Enter a decimal number: 19
Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.
Result:
Enter a decimal number: 19
Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary
need an explanation for this answer? contact us directly to get an explanation for this answer