Converting Decimal Numbers to Octal Numbers and Vice Versa in C++

Write a C++ program can display decimal numbers as octal numbers and octal numbers are decimal numbers.

1, decimal numbers to octal numbers

Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
long long DecimalToOctal(int);
int main()
{
    int num, ans;
    cout << "Insert any decimal number to be converted: "; 
    cin >> num;
    ans = DecimalToOctal(num);
    cout << num << " is " << ans << " in Octal " << endl ;
    return 0;
}
long long DecimalToOctal(int num)
{
    long long ans = 0;
    int y,x = 1;
    while (num!=0)
    {
        y = num%8;
        num /= 8;
        ans += y*x;
        x *= 10;
    }
    return ans;
}
Click Here to View the Output:
Insert any decimal number to be converted: 123
123 is 173 in Octal
Click Here to View the Explanation:
  • The user enters a number num to be converted to octal number.
  • A function DecimalToOctal is created using a while loop.
  • The function divide the number by 8 and stores the remainder in a variable y. The value of num is updated by further dividing it by 8.
  • ans was originally set to 0 and now y*x is added to ans and the value is updated again.
  • The value of x is also updated by multiplying it by 10.
  • The function is called in the main () function.

2. octal numbers as decimal numbers

Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
int OctalToDecimal(int num);
int main()
{
    int num;
    cout << "Insert an octal number to be converted: ";    
    cin >> num;
    cout << num << " is " << OctalToDecimal(num) << " in Decimal";
    return 0;
}
int OctalToDecimal(int num)
{
    int ans = 0, x = 0, Rem;
    while (num!=0)
    {
        Rem = num%10;
        num /= 10;
        ans += Rem*pow(8,x);
        ++x;
    }
    return ans;
}
Click Here to View the Output:
Insert an octal number to be converted: 173
 173 is 123 in Decimal
Click Here to View the Explanation:
  • The user is requested to enter a number to be converted and the entered number is stored as a variable num.
  • num is divided by 10 and the remainder is stored as Rem. num is divided by 10 and the new value is updated in the num variable.
  • ans is assigned a new value: ans = ans + Rem*pow(8,x)
  • The value of x is incremented by 1 through every iteration.
  • The function is called in the main () function.