In this tutorial, we will write a program to convert octal numbers into decimal numbers in C++. Before that, you must have knowledge of the following topics in C++.
Octal number
The octal numbers are the numbers with base 8 and use the digits 0 to 7. Example: 8 in decimal is represented as 10 in octal, 25 as 31, and so on.
Decimal Number
These are the numbers with a base of 10, which ranges from 0 to 9. These numbers are formed with the combination of 0 to 9 digits such as 24, 345, etc.
Let us go through a program for the Octal to Decimal Conversion in C++.
C++ Program to Convert Octal to Decimal Number
The program takes a user input for an octal number. And then iterate using a while loop. You can also use for loop instead of while loop, the code remains the same. Lastly, display the equivalent decimal value.
One of the libraries math functions (pow()
) is used. This function returns the value of power calculation maths. It is present in math.h
header file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> #include <math.h> using namespace std; int main() { int oct, deci = 0, i = 0, rem; cout << "Enter the Octal Number: "; cin >> oct; while (oct != 0) { rem = oct % 10; deci = deci + (rem* pow(8, i)); i++; oct = oct / 10; } cout << "Decimal Value: " << deci; return 0; } |
Output:
Enter the Octal Number: 10
Decimal Value: 8
You can also achieve the octal to decimal conversion using a function in C++. The way to do that is by creating a separate function where you pass the user entered octal value as an argument in a function.
After calculation, the function returns the decimal to the main function where the final result is displayed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | //convert octal to decimal using function in C++ #include <iostream> #include <cmath> using namespace std; // User defined function int conversionFunc(int oct) { int rem, deci = 0, i = 0; while (oct != 0) { rem = oct % 10; oct = oct / 10; deci = deci + (rem* pow(8, i)); ++i; } return deci; } //MAIN FUNCTION int main() { int octal, result; cout << "Enter an octal number: "; cin >> octal; //calling a function result = conversionFunc(octal); cout << "Decimal value: " << result; return 0; } |
Output:
Enter an octal number: 10
Decimal value: 8
You may go through the following program for vice-versa: