Convert Decimal to Octal

Decimal to Octal in C++ (4 Programs)

IntermediateTopic: Advanced Number Programs
Back

C++ Convert Decimal to Octal Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int decimal;
    long long octal = 0;
    int remainder, i = 1;
    
    cout << "Enter a decimal number: ";
    cin >> decimal;
    
    int temp = decimal;
    
    while (temp != 0) {
        remainder = temp % 8;
        temp /= 8;
        octal += remainder * i;
        i *= 10;
    }
    
    cout << "Decimal: " << decimal << " = Octal: " << octal << endl;
    
    return 0;
}
Output
Enter a decimal number: 10
Decimal: 10 = Octal: 12

Understanding Convert Decimal to Octal

This program teaches you how to convert a decimal number to its octal (base-8) equivalent in C++. Octal is a base-8 number system that uses digits 0-7. While less common than binary or decimal, octal is still used in Unix/Linux file permissions and some computing contexts. Understanding decimal-to-octal conversion helps you work with different number systems and system administration tasks.

---

1. What This Program Does

The program converts a decimal number (base-10) to an octal number (base-8). For example:

Input decimal: 10
Output octal: 12

The conversion involves repeatedly dividing the decimal number by 8 and collecting the remainders. The octal number is formed by reading the remainders in reverse order (from last to first).

Example:

10 (decimal) → divide by 8 repeatedly → remainders: 2, 1 → reverse → 12 (octal)
64 (decimal) → remainders: 0, 0, 1 → reverse → 100 (octal)

---

2. Header File Used

This header provides:

cout for displaying output
cin for taking input from the user

---

#include <iostream>

3. Declaring Variables

The program declares:

int decimal;

long long octal = 0;

int remainder, i = 1;

decimal stores the decimal number entered by the user.
octal stores the converted octal result (initialized to 0, long long for large results).
remainder stores the remainder from each division by 8.
i is a multiplier that represents the current position (1, 10, 100, 1000, ...).

---

4. Taking Input From the User

The program asks:

cin >> decimal;

The user enters a decimal number, for example: 10

We also create a temporary copy:

int temp = decimal;

This is important because we'll modify the number during conversion, and we need the original for display.

---

cout << "Enter a decimal number: ";

5. The Conversion Algorithm

The core conversion uses a while loop:

while (temp != 0) {

remainder = temp % 8;

temp /= 8;

octal += remainder * i;

i *= 10;

}

Let's break down how this works step-by-step for decimal = 10:

Step 1:

remainder = 10 % 8 = 2 (remainder when dividing by 8)
temp = 10 / 8 = 1 (quotient after dividing by 8)
octal = 0 + 2 × 1 = 2
i = 1 × 10 = 10 (move to next position)

Step 2:

remainder = 1 % 8 = 1
temp = 1 / 8 = 0
octal = 2 + 1 × 10 = 12
i = 10 × 10 = 100

Step 3:

temp is now 0, so the loop stops
Final result: octal = 12

---

6. Understanding the Conversion Process

Why Divide by 8?

:

Octal is base-8, so we divide by 8 repeatedly.
Each division extracts one octal digit (0-7) as the remainder.
The quotient becomes the new number to process.

Why Read Remainders in Reverse?

:

The first remainder is the least significant digit (rightmost).
The last remainder is the most significant digit (leftmost).
We build the octal number by placing remainders from right to left.

Visual Example

(for decimal = 10):

Step 1: 10 ÷ 8 = 1 remainder 2 → octal digit: 2
Step 2: 1 ÷ 8 = 0 remainder 1 → octal digit: 1
Reading remainders from bottom to top: 1, 2
Result: 12 (octal)

---

7. How the Octal Number is Built

Position Multiplier (i)

:

i starts at 1 (ones place).
Each iteration, i is multiplied by 10 (moves to next position).
i values: 1, 10, 100, 1000, 10000, ...

Building Process

:

remainder * i places the digit at the correct position.
Example: remainder = 1, i = 10 → adds 10 to octal (places 1 at tens place).
Each new remainder is placed to the left of previous digits.

Why Multiply i by 10?

:

We're building a number where each position is 10 times the previous.
This creates: ones, tens, hundreds, thousands, ...
Matches how we write numbers (right to left: ones, tens, hundreds, ...).

---

8. Other Methods (Mentioned but not shown in code)

Method 2: Using Recursion

long long decimalToOctal(int decimal) {

if (decimal == 0) return 0;

}

Recursive approach - function calls itself.
Base case: when decimal becomes 0, return 0.
Recursive case: get remainder, recurse on quotient, then combine.
    return (decimal % 8) + 10 * decimalToOctal(decimal / 8);

Method 3: Using stringstream with oct Manipulator

stringstream ss;

ss << oct << decimal;

string octalStr = ss.str();

long long octal = stoll(octalStr);

oct manipulator tells stream to interpret number as octal.
Actually converts decimal to octal string representation.
More advanced use of stream manipulators.
#include <sstream>
#include <iomanip>

Method 4: Using Functions

long long decimalToOctal(int decimal) {

}

Encapsulates conversion in a separate function.
Makes code more organized and testable.

---

    // Encapsulate conversion logic in function
    // Makes code modular and reusable

9. Displaying the Result

The program prints:

Output:

Decimal: 10 = Octal: 12

This clearly shows both the original decimal number and its octal equivalent.

---

cout << "Decimal: " << decimal << " = Octal: " << octal << endl;

10. Understanding the Division Process

Repeated Division by 8

:

Each division by 8 extracts one octal digit.
The remainder (0-7) is the octal digit.
The quotient is used for the next iteration.

When Does It Stop?

:

The process stops when the quotient becomes 0.
At this point, all octal digits have been extracted.

Example Trace

(for decimal = 64):

Step 1: 64 ÷ 8 = 8 remainder 0 → octal digit: 0
Step 2: 8 ÷ 8 = 1 remainder 0 → octal digit: 0
Step 3: 1 ÷ 8 = 0 remainder 1 → octal digit: 1
Step 4: 0 (stop)
Reading remainders from last to first: 1, 0, 0 → 100 (octal)

---

11. Common Decimal to Octal Conversions

Small Numbers

:

0 (decimal) = 0 (octal)
1-7 (decimal) = 1-7 (octal) (same for single digits)
8 (decimal) = 10 (octal)
9 (decimal) = 11 (octal)
10 (decimal) = 12 (octal)
16 (decimal) = 20 (octal)
64 (decimal) = 100 (octal)
512 (decimal) = 1000 (octal)

Pattern Recognition

:

Powers of 8 have single 1 followed by zeros: 8=10, 64=100, 512=1000
Numbers one less than power of 8 are all 7s: 7=7, 63=77, 511=777

---

12. When to Use Each Method

-

While Loop

: Best for learning - clear and straightforward, shows the algorithm.

-

Recursion

: Educational - helps understand recursive thinking.

-

stringstream with oct

: Advanced - demonstrates stream manipulators.

-

Functions

: Best for code organization - modular and reusable.

Best Practice

: Use while loop for learning, or functions for production code.

---

13. Important Considerations

Integer Overflow

:

Octal representation can be long for large decimals.
long long is used to handle larger octal numbers.
For very large decimals, consider using string method.

Leading Zeros

:

This method doesn't produce leading zeros.
Example: 8 (decimal) = 10 (octal), not 010.
If you need fixed width, pad with zeros manually.

Negative Numbers

:

This implementation doesn't handle negative numbers.
For negative numbers, convert absolute value and handle sign separately.

File Permissions

:

Unix/Linux file permissions use 3-digit octal.
Example: 755 (octal) = rwxr-xr-x permissions.
Understanding octal is essential for chmod command.

---

14. return 0;

This ends the program successfully.

---

Summary

Decimal-to-octal conversion repeatedly divides by 8 and collects remainders.
Remainders are read in reverse order (last to first) to form the octal number.
The algorithm processes from most significant to least significant digits.
Octal uses only digits 0-7 (base-8 number system).
Understanding this conversion is useful for file permissions and system administration.
Multiple methods exist: while loop, recursion, stringstream, functions.
Choose method based on needs: learning vs. code organization vs. simplicity.

This program is fundamental for beginners learning number systems, understanding positional notation, and preparing for system administration tasks, file permissions, and advanced computer science topics in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Convert Decimal to Octal

This C++ program is part of the "Advanced Number Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents