Convert Decimal to Octal

Decimal to Octal in C++

C++Intermediate
C++
#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

Convert Decimal to Octal in C++

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.

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)

Algorithm

The conversion uses a while loop:

cpp
while (temp != 0) {
    remainder = temp % 8;
    temp /= 8;
    octal += remainder * i;
    i *= 10;
}

Step-by-step for decimal = 10:

  1. Divide by 8: 10 % 8 = 2, octal = 2, i = 10
  2. Divide by 8: 1 % 8 = 1, octal = 12, i = 100
  3. Final result: octal = 12

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

File Permissions:

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

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.

This program is fundamental for understanding number systems, file permissions, and system administration tasks in C++.