C++ Online Compiler
Example: Decimal to Binary Conversion (Recursive) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Decimal to Binary Conversion (Recursive) #include <iostream> // Recursive function to convert decimal to binary void decToBinary(int n) { if (n == 0) { return; // Base case: nothing to do if number is 0 } decToBinary(n / 2); // Recurse with n divided by 2 std::cout << n % 2; // Print the remainder after the recursive call returns } int main() { // Step 1: Declare variable int decimalNum; // 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) { std::cout << "Binary equivalent: 0" << std::endl; } else { // Step 4: Call the recursive function std::cout << "Binary equivalent: "; decToBinary(decimalNum); std::cout << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS