C++ Code Example: convert decimal to binary number

This code is a simple implementation in C++ that converts a decimal number to binary.

Code Example

#include <iostream>
using namespace std;

int main() {
    int binaryArray[10], num, i;
    
    cout << "Please enter a number: ";
    cin >> num;

    for (i = 0; num > 0; i++) {
        binaryArray[i] = num % 2;
        num = num / 2;
    }
    cout << "Binary value of number " << num << " is ";
    for (i = i - 1; i >= 0; i--) {
        cout << binaryArray[i];
    }
}

Output

Please enter a number: 23
Binary value of number 0 is 10111

Code Explanation

    1. The main() function starts with the declaration of an integer array called binaryArray and two integer variables, num and i.
    2. The user is asked to enter a number using the cin statement. The input number is stored in the num variable.
    3. The next section of the code uses a for loop to convert the decimal number to binary. The loop continues until num becomes 0. The loop starts with i = 0.
    4. In each iteration of the loop, the value of num % 2 is stored in binaryArray[i]. This value represents the binary digit.
    5. The value of num is then divided by 2 using the num = num / 2 statement.
    6. The loop continues until num becomes 0, and the binary digits are stored in the binaryArray array.
    7. The final section of the code uses another for loop to print the binary digits in reverse order. The loop starts with i = i - 1 and continues until i >= 0.
    8. In each iteration of the loop, the binary digit stored in binaryArray[i] is printed using the cout statement.
    9. The main() function ends with a return 0 statement.