C++ Program To Convert Decimal To Binary - C++ Programming Tutorial
C++ Course / C++ Programs / C++ Program To Convert Decimal To Binary

C++ Program To Convert Decimal To Binary

BLUF: Mastering C++ Program To Convert Decimal To Binary is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Program To Convert Decimal To Binary

C++ is renowned for its efficiency. Learn how C++ Program To Convert Decimal To Binary enables low-level control and high-performance computing in the tutorial below.

We have the capability to transform any decimal numeral (base-10 (0 through 9)) into a binary numeral (base-2 (0 or 1)) using a C++ program.

Decimal Number

A decimal number is referred to as a base 10 number due to its range from 0 to 9, encompassing a total of 10 digits within this span. Any sequence of these digits represents a decimal number, for instance, 223, 585, 192, 0, 7, and so forth.

Binary Number

A binary number is classified as a base 2 numeral due to its exclusive use of 0s and 1s. Any sequence comprising solely of 0s and 1s represents a binary number, for instance, 1001, 101, 11111, 101010, and so forth.

Let's examine some binary representations for decimal numbers.

Decimal Binary
1 0
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010

Decimal to Binary Conversion Algorithm

Divide the given number by 2 using the modulus operator and save the resulting remainder in an array.

Divide the numerical value by 2 using the / (division operator).

Repeat the second step iteratively until the numerical value exceeds zero.

Let's examine the C++ demonstration for converting a decimal number to binary.

Example

Example

#include <iostream>

using namespace std;

int main()

{

int a[10], n, i;  

cout<<"Enter the number to convert: ";  

cin>>n;  

for(i=0; n>0; i++)  

{  

a[i]=n%2;  

n= n/2;

}  

cout<<"Binary of the given number= ";  

for(i=i-1 ;i>=0 ;i--)  

{  

cout<<a[i];  

}  

}

Output:

Output

Enter the number to convert: 9

Binary of the given number= 1001

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience