###### C++ Functions

C++ Program to Convert Octal Number to Decimal and vice-versa

# C++ Program to Convert Octal Number to Decimal and vice-versa

In this example, we will learn to convert octal number to decimal and decimal number to octal manually by creating a user-defined function.

To understand this example, you should have the knowledge of the following C++ programming topics:

## Example 1: Program to 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 1

```Enter an octal number: 2341
2341 in octal = 1249 in decimal```

##### Working

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: Program to 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 1

```Enter an decimal number: 78
78 in decimal = 116 in octal```

##### Working

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.

## Next Example

We hope that this Example helped you develop better understanding of the concept of "Convert Octal Number to Decimal and vice-versa" in C++.

Keep Learning : )

In the next Example, we will learn about C++ `Convert Binary Number to Octal and vice-versa`.