The C++ Programming Language

Decimal to Binary Example Program

Click below to go directly to a specific section:
Description | Source Code | Sample Run | Program Notes


This program takes a positive integer and recursively converts it to it's binary equivalent and displays the result.

Source Code

#include <iostream.h>

void binary(int);

void main(void) {
	int number;

	cout << "Please enter a positive integer: ";
	cin >> number;
	if (number < 0) 
		cout << "That is not a positive integer.\n";
	else {
		cout << number << " converted to binary is: ";
		cout << endl;

void binary(int number) {
	int remainder;

	if(number <= 1) {
		cout << number;

	remainder = number%2;
	binary(number >> 1);    
	cout << remainder;

Sample Run

Please enter a positive integer value: 24
24 converted to binary is: 11000

Program Notes

This program prompts the user for a positive integer. The function binary divides the integer by 2 (using the bitshift operation) until the number becomes 1, at which point it outputs 1 and steps back thru the function calls outputting the remainder from previous divisions. This program has been tested and works for all integers within C++ limits.
[Back] [Home]

Last modified: 06:12 PM on 09/17/1999