C++ Program to Convert Decimal to Octal Number
cout.Examples
How to Think About It
Algorithm
Code
#include <iostream> #include <vector> using namespace std; int main() { int decimal; cout << "Enter a decimal number: "; cin >> decimal; if (decimal == 0) { cout << 0 << endl; return 0; } vector<int> octalDigits; int num = decimal; while (num > 0) { octalDigits.push_back(num % 8); num /= 8; } cout << "Octal equivalent: "; for (int i = octalDigits.size() - 1; i >= 0; i--) { cout << octalDigits[i]; } cout << endl; return 0; }
Dry Run
Let's trace the decimal number 65 through the code to see how it converts to octal.
Input
decimal = 65
Check if zero
65 is not zero, continue
First division
65 / 8 = 8 remainder 1; store 1
Second division
8 / 8 = 1 remainder 0; store 0
Third division
1 / 8 = 0 remainder 1; store 1
Stop division
Quotient is 0, stop
Print octal
Print stored remainders in reverse: 1 0 1
| Quotient | Remainder | Stored Remainders |
|---|---|---|
| 65 / 8 = 8 | 1 | [1] |
| 8 / 8 = 1 | 0 | [1, 0] |
| 1 / 8 = 0 | 1 | [1, 0, 1] |
Why This Works
Step 1: Divide by 8
Dividing the decimal number by 8 gives the remainder which is the least significant octal digit.
Step 2: Store remainders
Each remainder is stored in a list to keep track of octal digits from right to left.
Step 3: Reverse order
Printing the stored remainders in reverse order forms the correct octal number.
Alternative Approaches
#include <iostream> using namespace std; void decimalToOctal(int num) { if (num == 0) return; decimalToOctal(num / 8); cout << num % 8; } int main() { int decimal; cout << "Enter a decimal number: "; cin >> decimal; if (decimal == 0) cout << 0; else decimalToOctal(decimal); cout << endl; return 0; }
#include <iostream> #include <bitset> using namespace std; int main() { int decimal; cout << "Enter a decimal number: "; cin >> decimal; if (decimal == 0) { cout << 0 << endl; return 0; } string octal = ""; int num = decimal; while (num > 0) { octal = to_string(num % 8) + octal; num /= 8; } cout << "Octal equivalent: " << octal << endl; return 0; }
Complexity: O(log n) time, O(log n) space
Time Complexity
The number of divisions by 8 depends on the size of the decimal number, roughly proportional to log base 8 of the number.
Space Complexity
We store each remainder in a vector or string, so space grows with the number of octal digits, also O(log n).
Which Approach is Fastest?
Both iterative and recursive methods have similar time complexity; iterative is usually preferred for clarity and stack safety.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative with vector | O(log n) | O(log n) | Clear and easy to understand |
| Recursive | O(log n) | O(log n) | Elegant but uses call stack |
| String concatenation | O(log n) | O(log n) | Simple but less efficient due to string operations |