Header Ads Widget

Ticker

6/recent/ticker-posts

C++ Program to convert Decimal to Binary Notes+Coding by Digitalise Data

 

C++ Program to convert Decimal to Binary Notes+Coding by Digitalise Data

C++ Program to convert Decimal to Binary

We can convert any decimal number (base-10 (0 to 9)) into binary number (base-2 (0 or 1)) by C++ program.

Decimal Number

Decimal number is a base 10 number because it ranges from 0 to 9, there are total 10 digits between 0 to 9. Any combination of digits is decimal number such as 223, 585, 192, 0, 7 etc.

Binary Number

Binary number is a base 2 number because it is either 0 or 1. Any combination of 0 and 1 is binary number such as 1001, 101, 11111, 101010 etc.

Let's see the some binary numbers for the decimal number.

DecimalBinary
10
210
311
4100
5101
6110
7111
81000
91001
101010

Decimal to Binary Conversion Algorithm

Step 1: Divide the number by 2 through % (modulus operator) and store the remainder in array

Step 2: Divide the number by 2 through / (division operator)

Step 3: Repeat the step 2 until the number is greater than zero

Let's see the C++ example to convert decimal to binary.

  1. #include <iostream.h>
  2. #include <conio.h>
  3. void main()  
  4. {  
  5. int a[10], n, i;    
  6. cout<<"Enter the number to convert: ";    
  7. cin>>n;    
  8. for(i=0; n>0; i++)    
  9. {    
  10. a[i]=n%2;    
  11. n= n/2;  
  12. }    
  13. cout<<"Binary of the given number= ";    
  14. for(i=i-1 ;i>=0 ;i--)    
  15. {    
  16. cout<<a[i];    
  17. }    
  18. getch();
  19. }  

Output:

Enter the number to convert: 9
Binary of the given number= 1001

Post a Comment

0 Comments