Example 1: Convert Octal Number to Decimal
#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;
}
Output
Enter an octal number: 2341 2341 in octal = 1249 in decimal
In the program, the octal number is stored in the variable octalNumber and passed to function octalToDecimal()
.
This function converts the octal number passed by user to its equivalent decimal number and returns it to main()
function.
Example 2: Convert Decimal Number to Octal
#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;
}
Output
Enter an decimal number: 78 78 in decimal = 116 in octal
In the program, the decimal number is stored in the variable decimalNumber and passed to function decimalToOctal()
.
This function converts the decimal number passed by user to its equivalent octal number and returns it to main()
function.