Google News
logo
C++ Program to Convert Octal Number to Decimal and Vice-Versa
In the following example of C++ program to convert an octal number to decimal and vice versa :
Program :
#include <iostream>
#include <cmath>
using namespace std;

// function to convert octal to decimal
int octalToDecimal(int n) {
    int decimal = 0, i = 0;

    while (n > 0) {
        int digit = n % 10;
        decimal += digit * pow(8, i);
        n /= 10;
        i++;
    }

    return decimal;
}

// function to convert decimal to octal
int decimalToOctal(int n) {
    int octal = 0, i = 0;

    while (n > 0) {
        int digit = n % 8;
        octal += digit * pow(10, i);
        n /= 8;
        i++;
    }

    return octal;
}

int main() {
    int choice, n;

    cout << "Choose an option:\n";
    cout << "1. Octal to Decimal\n";
    cout << "2. Decimal to Octal\n";
    cin >> choice;

    switch (choice) {
        case 1:
            cout << "Enter an octal number: ";
            cin >> n;
            cout << "Decimal equivalent: " << octalToDecimal(n) << endl;
            break;

        case 2:
            cout << "Enter a decimal number: ";
            cin >> n;
            cout << "Octal equivalent: " << decimalToOctal(n) << endl;
            break;

        default:
            cout << "Invalid choice.\n";
            break;
    }

    return 0;
}
Output :
Choose an option:
1. Octal to Decimal
2. Decimal to Octal

1
Enter an octal number: 10121
Decimal equivalent: 4177

 

Choose an option:
1. Octal to Decimal
2. Decimal to Octal

2
Enter a decimal number: 4177
Octal equivalent: 10121
This program prompts the user to choose between converting an octal number to decimal or a decimal number to octal. Depending on the choice, the program either calls octalToDecimal or decimalToOctal to perform the conversion. octalToDecimal converts an octal number to decimal using the formula:

decimal = digit<sub>0</sub> * 8<sup>0</sup> + digit<sub>1</sub> * 8<sup>1</sup> + ... + digit<sub>n-1</sub> * 8<sup>n-1</sup>

where digit<sub>i</sub> is the i-th digit from the right in the octal number. decimalToOctal converts a decimal number to octal by repeatedly dividing by 8 and keeping track of the remainders. The octal number is then constructed by concatenating the remainders in reverse order.