Decimal to Binary

To convert a decimal number to binary in C++, you can follow these steps:

  1. Take the decimal number as input from the user.
  2. Create an empty string to store the binary representation.
  3. Perform repeated division by 2 until the decimal number becomes zero.
  4. At each step of division, store the remainder (0 or 1) in the binary string.
  5. Reverse the binary string to get the final binary representation.

Here is an example implementation:

#include <iostream>
#include <string>
using namespace std;

string decimalToBinary(int decimal) {
    string binary = "";

    while (decimal > 0) {
        int remainder = decimal % 2;
        binary += to_string(remainder);
        decimal /= 2;
    }

    reverse(binary.begin(), binary.end());

    return binary;
}

int main() {
    int decimal;
    cout << "Enter a decimal number: ";
    cin >> decimal;

    string binary = decimalToBinary(decimal);
    cout << "Binary representation: " << binary << endl;

    return 0;
}

In this example, the decimalToBinary function takes an integer decimal as input and returns a string representing its binary equivalent. The function uses a while loop to perform repeated division by 2 until the decimal number becomes zero. The remainder at each step is appended to the binary string. Finally, the binary string is reversed to get the correct binary representation.

The main function prompts the user to enter a decimal number, calls the decimalToBinary function to convert it to binary, and prints the result.