Decimal To Binary in C++


Q. Write a C++ program decimal to binary ?

#include <iostream>   
using namespace std;
  
int main(){ 
    int n,i,l;
    int b[1000];
    cout << "Enter an integer in decimal number system:";
    cin >> n;
    l=n;
    for (i=0; n>0; i++)
    {
        b[i]=n%2;
        n=n/2;
    }
    cout << l << " in binary number system is: " ;
    for(int j=i-1; j>=0; j--)
    {
        cout << b[j];
    }
	return 0;    
} 

Q. Write an algorithm to decimal to binary in C++?

1. Start 
2. Read input:
    - Prompt the user to enter a decimal integer `n`. 
3. Initialize variables:
    - Store the original value of `n` in a variable, say `l`, for later output.
    - Create an array `b` to store binary digits (bits).
    - Initialize a counter `i` to 0. 
4. Convert decimal to binary:
   - While `n > 0` do the following:
   a. `b[i] = n % 2` (Store remainder of `n` divided by 2 in `b[i]`)
   b. `n = n / 2` (Integer division by 2)
   c. Increment `i` by 1. 
5. Output binary digits:
   - Print the stored original decimal number `l` followed by a message indicating the binary equivalent.
   - Loop from `i-1` down to `0`:
   - Print the `b[j]` bits in reverse order to get the correct binary number. 
6. End 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.