Algorithm


Convert Octal to Decimal:

Input:
Accept the octal number as input.

Initialization:
Initialize a variable decimal to store the decimal equivalent.
Initialize a variable base to 1, representing the base of octal number system.

Conversion:
Starting from the rightmost digit of the octal number:
Multiply each digit by the corresponding power of 8 (base^position).
Add the result to the decimal variable.
Update the base for the next position.

Output:
Print the decimal equivalent.


Convert Decimal to Octal:

Input:
Accept the decimal number as input.

Initialization:
Initialize an array octalDigits to store the octal digits.
Initialize a variable decimal to the input decimal number.

Conversion:
Until decimal is greater than 0:
Divide decimal by 8.
Store the remainder (which is an octal digit) in the octalDigits array.
Update decimal to the quotient.

Output:
Print the octal digits in reverse order (from the last computed digit to the first).

Code Examples

#1 Code Example- Convert Octal Number to Decimal

Code - C++ Programming

#include <iostream>
#include <cmath>
using namespace std;

int octalToDecimal(int octalNumber);

int main()
{
   int octalNumber;
   cout << "Enter an octal number: ";
   cin >> octalNumber;
   cout << octalNumber << " in octal = " << octalToDecimal(octalNumber) << " in decimal";
   
   return 0;
}

// Function to convert octal number to decimal
int octalToDecimal(int octalNumber)
{
    int decimalNumber = 0, i = 0, rem;
    while (octalNumber != 0)
    {
        rem = octalNumber % 10;
        octalNumber /= 10;
        decimalNumber += rem * pow(8, i);
        ++i;
    }
    return decimalNumber;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter an octal number: 2341
2341 in octal = 1249 in decimal

#2 Code Example- Convert Decimal Number to Octal

Code - C++ Programming

#include <iostream>
#include <cmath>
using namespace std;

int decimalToOctal(int decimalNumber);

int main()
{
   int decimalNumber;
   cout << "Enter a decimal number: ";
   cin >> decimalNumber;
   cout << decimalNumber << " in decimal = " << decimalToOctal(decimalNumber) << " in octal";
   
   return 0;
}

// Function to convert decimal number to octal
int decimalToOctal(int decimalNumber)
{
    int rem, i = 1, octalNumber = 0;
    while (decimalNumber != 0)
    {
        rem = decimalNumber % 8;
        decimalNumber /= 8;
        octalNumber += rem * i;
        i *= 10;
    }
    return octalNumber;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter an decimal number: 78
78 in decimal = 116 in octal
Advertisements

Demonstration


C++ Programing Example to Convert Octal Number to Decimal and vice-versa-DevsEnv