C++ Program: Decimal to Binary
In this program, we convert a decimal (base 10) number to binary (base 2) using C++.
Syntax
#include <iostream>
using namespace std;
int main()
{
int decimal;
cout << "Enter a decimal number: ";
cin >> decimal;
int binary[32];
int index = 0;
while(decimal > 0) {
binary[index] = decimal % 2;
decimal = decimal / 2;
index++;
}
cout << "Binary representation: ";
for(int i = index - 1; i >= 0; i--){
cout << binary[i];
}
return 0;
}
Example
Let's convert the decimal number 23 to binary using this program.
Enter a decimal number: 23
Binary representation: 10111
Explanation
We first prompt the user to enter a decimal number. Then, we declare an integer array called "binary" with size 32 to store the binary digits. We also declare an integer variable called "index" to keep track of the array index.
We then use a while loop to convert the decimal number to binary. Inside the loop, we take the modulus of the decimal number with 2, which gives us the binary digit (either a 0 or a 1). We store this digit in the next available index in the "binary" array and then divide the decimal number by 2 to get the next digit. We repeat this process until the decimal number becomes zero.
Finally, we print the binary representation of the decimal number by printing the elements of the "binary" array in reverse order.
Use
This program can be used to convert decimal numbers to binary numbers for further processing.
Important Points
- The binary representation of a decimal number can have up to 32 digits.
- The array index is incremented after each binary digit is stored.
- The binary representation is printed in reverse order.
Summary
In conclusion, this program is a simple and effective way to convert decimal numbers to binary numbers using C++. It can be used for various applications, such as binary arithmetic and data storage.