Placement Prep

Decimal to Octal Conversion in C, C++, Java, and Python

Step-by-step decimal to octal conversion in C, C++, Java, and Python: division algorithm, built-in functions, and where this appears in placement coding tests.

By FACE Prep Team 5 min read
decimal-to-octal number-systems c-programming cpp-programming java-programming python-programming placement-prep

Decimal-to-octal conversion follows a single algorithm: divide the number by 8 repeatedly, collect the remainders, and read them in reverse.

The four code samples below implement that algorithm in C, C++, Java, and Python, plus the built-in shortcut each language provides.

How the Conversion Algorithm Works

Octal is base 8, so each digit position represents a successive power of 8: the rightmost digit is the ones place (8^0 = 1), the next is the eights place (8^1 = 8), then 64, 512, and so on.

To convert a decimal number to its octal equivalent, divide repeatedly by 8 and collect each remainder. The octal result is those remainders read from last to first.

Worked example for 200:

  • Step 1: 200 ÷ 8 = 25, remainder 0
  • Step 2: 25 ÷ 8 = 3, remainder 1
  • Step 3: 3 ÷ 8 = 0, remainder 3
  • Read remainders bottom-to-top: 310
  • Verification: 3 × 64 + 1 × 8 + 0 × 1 = 192 + 8 + 0 = 200

The algorithm terminates when the quotient reaches 0. A second example shows a power of 8:

Worked example for 512:

  • Step 1: 512 ÷ 8 = 64, remainder 0
  • Step 2: 64 ÷ 8 = 8, remainder 0
  • Step 3: 8 ÷ 8 = 1, remainder 0
  • Step 4: 1 ÷ 8 = 0, remainder 1
  • Read remainders bottom-to-top: 1000
  • Verification: 1 × 512 = 512

512 is 8 cubed, so it maps to 1000 in octal. The same relationship holds in base 10: 1000 is 10 cubed. This pattern is a useful sanity check: powers of 8 always produce 1 followed by zeros in octal.

A quick reference table for common conversions:

DecimalOctal
810
64100
200310
255377
5121000

Decimal to Octal in C

The standard approach stores each remainder in an array, then prints the array in reverse.

#include <stdio.h>

void decimal_to_octal(int n) {
    int rem[32];
    int i = 0;
    if (n == 0) {
        printf("0\n");
        return;
    }
    while (n > 0) {
        rem[i++] = n % 8;
        n /= 8;
    }
    for (int j = i - 1; j >= 0; j--)
        printf("%d", rem[j]);
    printf("\n");
}

int main(void) {
    decimal_to_octal(8);    /* Output: 10   */
    decimal_to_octal(200);  /* Output: 310  */
    decimal_to_octal(512);  /* Output: 1000 */
    return 0;
}

The array size of 32 is sufficient: the largest signed 32-bit integer (about 2.1 billion) requires at most 11 octal digits.

Built-in Shortcut in C

The %o format specifier in printf prints an integer directly as octal. No loop required:

printf("%o\n", 200);   /* Output: 310  */
printf("%o\n", 512);   /* Output: 1000 */

Use the manual function when you need the octal digits as a string in memory. Use %o when you only need to display the result.

Decimal to Octal in C++

C++ adds the oct stream manipulator, which shifts cout to base-8 output until explicitly reset. The manual implementation using std::string and reverse() mirrors the C approach:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string decimal_to_octal(int n) {
    if (n == 0) return "0";
    string result;
    while (n > 0) {
        result += (char)('0' + n % 8);
        n /= 8;
    }
    reverse(result.begin(), result.end());
    return result;
}

int main() {
    cout << decimal_to_octal(200) << "\n";  // 310

    // Built-in shortcut
    cout << oct << 200 << "\n";            // 310
    cout << dec;                           // reset to decimal
    return 0;
}

Notes on the C++ Implementation

  • reverse() from <algorithm> handles the bottom-to-top reading in one call, avoiding a second explicit loop.
  • oct sets the base for all subsequent cout output. Resetting with cout << dec prevents hard-to-find bugs later in the same program.
  • The character cast (char)('0' + n % 8) works because octal digits are 0 through 7, all consecutive ASCII characters.

Decimal to Octal in Java

Java’s standard library provides Integer.toOctalString(n), documented in the Java SE 8 API. The manual implementation below shows the same algorithm for comparison:

public class DecimalToOctal {
    static String decimalToOctal(int n) {
        if (n == 0) return "0";
        StringBuilder sb = new StringBuilder();
        while (n > 0) {
            sb.append(n % 8);
            n /= 8;
        }
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        int n = 200;
        System.out.println(decimalToOctal(n));          // 310
        System.out.println(Integer.toOctalString(n));   // 310
    }
}

StringBuilder.reverse() handles the bottom-to-top reading in one method call. Coding tests that ask you to implement the conversion from scratch want the loop; tests that only ask for the output accept either form.

When n is negative, Integer.toOctalString() interprets the value as an unsigned 32-bit integer, which produces a different result than the signed interpretation. The manual loop above will produce an empty string for negative inputs. For placement-test purposes, assume n >= 0 unless told otherwise.

Decimal to Octal in Python

Python’s oct() built-in returns the octal string with a 0o prefix. Use [2:] to strip the prefix when you need a plain numeric string:

def decimal_to_octal(n):
    if n == 0:
        return "0"
    digits = []
    while n > 0:
        digits.append(n % 8)
        n //= 8
    return ''.join(str(d) for d in reversed(digits))

n = 200
print(decimal_to_octal(n))   # 310
print(oct(n))                 # 0o310
print(oct(n)[2:])             # 310

The integer floor-division operator // keeps n as an integer rather than a float, which matters when the loop condition checks n > 0. Using / instead would produce a float that never reaches exactly zero.

Python’s oct() handles negative numbers with a leading minus sign: oct(-8) returns '-0o10'. The manual implementation above will loop forever on negative input because n stays negative and n > 0 is never true. Add a guard (if n < 0: return '-' + decimal_to_octal(-n)) if your inputs can be negative.

Time and Space Complexity

ImplementationTimeSpace
Manual (all four languages)O(log n) base 8O(log n) — storage for the digit array or string
C printf("%o")O(log n) base 8O(1) — no user-space digit storage
Java Integer.toOctalStringO(log n) base 8O(log n) — internal string allocation
Python oct()O(log n) base 8O(log n) — string allocation

The loop runs exactly floor(log base 8 of n) + 1 times for any positive integer n. For a 32-bit integer, that is at most 11 iterations.

Number Systems in Placement Tests

Number-system conversion (decimal-to-binary, decimal-to-octal, octal-to-decimal) appears in AMCAT’s quantitative section and in the aptitude rounds of service-tier company tests. The question format is typically short: “What is the octal equivalent of 512?” or “Convert 377 octal to decimal.” Worked examples in both directions, with the verification step, are the fastest way to become fluent.

Coding platforms handle this problem two ways. Some restrict built-ins and expect a manual implementation with the division loop; others accept any working solution. The difference matters in timed rounds. If you see a platform that allows %o, oct(), or Integer.toOctalString(), using the built-in is not cheating. It is exactly the kind of pragmatic judgment that interviewers value.

Number-system questions rarely appear in isolation. They are often bundled with other programming exercises in the same 45-minute session. Familiarity with data structures interview questions, array element problems, and palindrome checks rounds out the typical mix.

Writing the conversion from scratch in Python takes five lines. Writing it with oct() takes one. Knowing when to reach for each form, and being able to explain the division algorithm when asked, is the real skill being assessed. TinkerLLM puts both versions in front of you in a single coding session, starting at ₹299.

Primary sources

Frequently asked questions

What is the octal representation of decimal 200?

Octal 310. Divide: 200÷8=25 rem 0, 25÷8=3 rem 1, 3÷8=0 rem 3. Read remainders in reverse: 310. Verify: 3×64 + 1×8 + 0×1 = 200.

How do I remove the '0o' prefix from Python's oct() output?

Use oct(n)[2:] to slice off the first two characters. For example, oct(200) returns '0o310', and oct(200)[2:] returns '310'.

Can I print octal directly in C without writing a conversion function?

Yes. printf("%o", n) prints the integer n as an octal string. %o is the standard octal format specifier in both C and C++.

What is the time complexity of decimal-to-octal conversion?

O(log n) base 8 — the number of iterations equals the number of digits in the octal result, which equals floor(log base 8 of n) + 1 for any positive integer.

Does the algorithm work correctly when the input is 0?

The while-loop does not execute for n=0, producing an empty result. Handle this as a special case: if n == 0, return '0' before entering the loop.

What is the octal equivalent of decimal 255?

Octal 377. Divide: 255÷8=31 rem 7, 31÷8=3 rem 7, 3÷8=0 rem 3. Read in reverse: 377. Verify: 3×64 + 7×8 + 7×1 = 192 + 56 + 7 = 255.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF