C++ Online Compiler
Example: Decimal to Binary Conversion (Iterative) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Decimal to Binary Conversion (Iterative) #include <iostream> #include <string> #include <algorithm> // Required for std::reverse int main() { // Step 1: Declare variables int decimalNum; std::string binaryString = ""; // Step 2: Prompt user for input std::cout << "Enter a positive decimal number: "; std::cin >> decimalNum; // Step 3: Handle the special case of 0 if (decimalNum == 0) { binaryString = "0"; } else { // Step 4: Perform conversion using modulo and division while (decimalNum > 0) { int remainder = decimalNum % 2; // Get the remainder binaryString += std::to_string(remainder); // Convert remainder to string and append decimalNum /= 2; // Divide the number by 2 } // Step 5: Reverse the binary string as remainders are collected in reverse order std::reverse(binaryString.begin(), binaryString.end()); } // Step 6: Display the result std::cout << "Binary equivalent: " << binaryString << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS