C++ Online Compiler
Example: Octal to Decimal Converter in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Octal to Decimal Converter #include <iostream> #include <cmath> // Not strictly necessary for this approach, but often used for powers int main() { long long octalNumber; std::cout << "Enter an octal number: "; std::cin >> octalNumber; long long decimalNumber = 0; long long power = 1; // Corresponds to 8^0 initially // Step 1: Loop while the octal number is greater than 0 while (octalNumber > 0) { // Step 2: Get the last digit of the octal number int lastDigit = octalNumber % 10; // Step 3: Check for invalid octal digit (must be 0-7) if (lastDigit >= 8) { std::cout << "Error: Invalid octal digit detected." << std::endl; return 1; // Exit with an error code } // Step 4: Multiply the last digit by the current power of 8 and add to decimal number decimalNumber += lastDigit * power; // Step 5: Update power to the next power of 8 (8^1, 8^2, etc.) power *= 8; // Step 6: Remove the last digit from the octal number octalNumber /= 10; } std::cout << "Decimal equivalent: " << decimalNumber << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS