Write a C++ Program to Convert Octal Number to Decimal and vice-versa

Converting numbers from one base to another is a common task in computer programming.

In this tutorial, we will discuss how to convert octal numbers to decimal and vice versa using C++.

Octal to Decimal Conversion:

Octal numbers are base 8 numbers, which means they use 8 digits, i.e., 0, 1, 2, 3, 4, 5, 6, and 7.

To convert an octal number to decimal, we need to follow the below steps:

  • Take the octal number as input.
  • Initialize a variable named decimal to zero.
  • Multiply each digit of the octal number starting from the rightmost digit by increasing powers of 8 (starting from 8^0) and add the result to the decimal variable.
  • Repeat step 3 until all digits of the octal number have been processed.
  • The value of the decimal variable is the decimal equivalent of the octal number.

Let’s see the code for the same:

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int octal, decimal = 0, i = 0;
    cout<<"Enter an octal number: ";
    cin>>octal;
    while(octal != 0)
    {
        decimal += (octal%10) * pow(8,i);
        ++i;
        octal/=10;
    }
    cout<<"The decimal equivalent is: "<<decimal;
    return 0;
}

Decimal to Octal Conversion:

Decimal numbers are base 10 numbers, which means they use 10 digits, i.e., 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. To convert a decimal number to octal, we need to follow the below steps:

  • Take the decimal number as input.
  • Initialize a variable named octal to zero.
  • Divide the decimal number by 8 and keep track of the remainder.
  • Add the remainder to the rightmost position of the octal number.
  • Repeat step 3 and 4 until the quotient becomes zero.
  • The octal number is the result obtained by writing the remainders in reverse order.

Let’s see the code for the same:

#include<iostream>
using namespace std;
int main()
{
    int decimal, octal = 0, i = 1;
    cout<<"Enter a decimal number: ";
    cin>>decimal;
    while(decimal != 0)
    {
        octal += (decimal%8) * i;
        decimal /= 8;
        i *= 10;
    }
    cout<<"The octal equivalent is: "<<octal;
    return 0;
}

Conclusion

In this blog post, we have discussed how to convert octal numbers to decimal and vice versa using C++.

The process involves a set of simple steps that can be implemented easily in C++.