C++: Example: Convert to binary by division

This program reads integers and prints them in binary, altho it prints the bits in reverse order. This isn't a useful program - it is simply used to illustrate a few concepts.
  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 
// to-binary-reversed.cpp - Convert decimal to binary by repeated mod, div.
// Fred Swartz - 2001-09-04
// This algorithm prints the bits from low to high order.
//      Improvements on the order have to wait until
//      bit operations, arrays or strings, functions, etc
//      Doesn't work with negative numbers or zero.

#include <iostream>
using namespace std;

int main() {
    int n;  // number to convert to binary

    while (cin >> n) {
        if (n > 0) {
            cout << n << " (decimal) = ";
    
            while (n > 0) {
                cout << n%2;
                n = n/2;
            }
    
            cout << " (binary) in reverse order" << endl;
        } else {
            cout << "Please enter a number greater than zero." << endl;
        }
    }
  return 0;
}//end main
The text from the above example can be selected, copied, and pasted into an editor.

Programming Exercises

This isn't really a very good program. Here are some modifications you might want to try.
  1. This doesn't print anything if the initial value is zero. Because you always want to go thru the loop once, it is a perfect application for the do...while statement.
  2. This algorithm can not be easily modified to print negative numbers in their internal native form, but you could modify this to show a signed form of binary numbers by writing out a minus sign followed by the positive form of the number.

See also

Convert to binary with bit-ops.