Monday, December 14, 2015

Programming Corner: How To Convert Decimal To Binary In C++ With Ease

The following program shows how you can convert any number in decimal (Base 10) to binary (Base 2) with ease. 

Steps:

/*
    This serves as a comment: This program converts decimal to binary
*/
#include<iostream>
using namespace std;
void binary(int num)

{
    int rem;
    if (num <= 1)
    {
        cout << num;
        return;
    }
    rem = num % 2;
    binary(num / 2);
    cout << rem;
}
int main()
{
    int dec, bin;
    cout << "Enter the number : ";
    cin >> dec;
    if (dec < 0)
        cout << dec << " is not a positive integer." << endl;
    else
    {
        cout << "The binary form of " << dec << " is ";
        binary(dec);
        cout << endl;
    }
    return 0;
}




The OUTPUT will be:

  • Enter the number: (cursor will be blinking here, you can introduce any number in decimal
  • The binary form of (the number entered in decimal)  is (answer will be displayed in binary)


No comments:

Post a Comment

Please share your thoughts by clicking on POST A COMMENT link or posting in FACEBOOK COMMENT BOX above:


DISCLAIMER:

Opinions expressed in comments are strictly those of the comment writers alone and does not reflect or represent the views of PoliFocus.

Calling the CONTACTS on the comments is at your own risk, PoliFocus is not liable for any SCAM that may arise in the course of that.