#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;
}
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
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>
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.