converting decimal to binary in cpp

To convert a decimal number to binary in C++, you can use the following steps:

  1. Input the decimal number: Start by taking an input from the user, which represents the decimal number that you want to convert to binary.

  2. Initialize variables: Declare and initialize variables to store the decimal number and the binary representation.

int decimalNumber;
std::string binaryNumber = "";
  1. Perform the conversion: Use a loop to repeatedly divide the decimal number by 2 and store the remainders. The loop should continue until the decimal number becomes 0.
while (decimalNumber > 0) {
    int remainder = decimalNumber % 2;
    decimalNumber /= 2;
    binaryNumber = std::to_string(remainder) + binaryNumber;
}
  1. Output the binary number: After the loop finishes, the binaryNumber variable will contain the binary representation of the decimal number. You can output it to the console or use it for further processing as needed.
std::cout << "The binary representation is: " << binaryNumber << std::endl;

Here is the complete code example:

#include <iostream>
#include <string>

int main() {
    int decimalNumber;
    std::string binaryNumber = "";

    std::cout << "Enter a decimal number: ";
    std::cin >> decimalNumber;

    while (decimalNumber > 0) {
        int remainder = decimalNumber % 2;
        decimalNumber /= 2;
        binaryNumber = std::to_string(remainder) + binaryNumber;
    }

    std::cout << "The binary representation is: " << binaryNumber << std::endl;

    return 0;
}

This code will convert the decimal number entered by the user into its binary representation.