Decimal to Octal Conversion in C++
Decimal to Octal Conversion
Decimal to Octal conversion is the process of converting a decimal number (base-10) into its equivalent octal number (base-8). Each octal digit represents a power of 8.
For example, the decimal number 31 is equal to octal 37 because:
(3 × 8¹) + (7 × 8⁰) = 24 + 7 = 31
We will explore three methods to convert a decimal number to an octal number using C++ programming.
Method 1: Using Division by 8
We divide the decimal number by 8 repeatedly, storing the remainders. These remainders represent the digits of the octal number from least significant to most significant.
#include <iostream> #includeusing namespace std; void decimalToOctal(int decimal) { vector octal; while (decimal > 0) { octal.push_back(decimal % 8); decimal = decimal / 8; } cout << "Octal equivalent: "; for (int i = octal.size() - 1; i >= 0; i--) { cout << octal[i]; } cout << endl; } int main() { int decimal; cout << "Enter a decimal number: "; cin >> decimal; decimalToOctal(decimal); return 0; }
Output:
Enter a decimal number: 31 Octal equivalent: 37
Method 2: Using std::oct (C++'s built-in feature)
C++ provides a built-in way to print numbers in octal format using the std::oct manipulator.
#include <iostream> using namespace std; int main() { int decimal; cout << "Enter a decimal number: "; cin >> decimal; cout << "Octal equivalent: " << std::oct << decimal << endl; return 0; }
Output:
Enter a decimal number: 31 Octal equivalent: 37
Method 3: Using Recursion
We can convert a decimal number to octal recursively. The recursive function divides the number by 8 and prints the remainders, which form the octal digits.
#include <iostream> using namespace std; void decimalToOctalRecursive(int decimal) { if (decimal == 0) { return; } decimalToOctalRecursive(decimal / 8); cout << decimal % 8; } int main() { int decimal; cout << "Enter a decimal number: "; cin >> decimal; if (decimal == 0) { cout << "Octal equivalent: 0" << endl; } else { cout << "Octal equivalent: "; decimalToOctalRecursive(decimal); cout << endl; } return 0; }
Output:
Enter a decimal number: 31 Octal equivalent: 37