C++ Program For Decimal To Octal Conversion
Last Updated :
03 Aug, 2023
The octal numbers are a base 8 number system that uses digits from 0-7 and the decimal numbers are a base 10 numbers system that uses 10 digits from 0-9 to represent any numeric value.
In this article, we will learn how to write a C++ program to convert a given decimal number into an equivalent octal number. i.e. convert the number with base value 10 to base value 8.
Algorithm to Convert Decimal Numbers to Octal in C++
- Create an array to store the octal representation.
- Run a loop till the number is not zero.
- Extract the remainder by taking the mod of the number by 8 and store the remainder in the array as an octal digit.
- Update the number by dividing it by 8 in each iteration.
- Print the array in reverse order.
The below diagram shows an example of converting the decimal number 33 to an equivalent octal number.
C++ Program to Convert Decimal Number To Octal Number
C++
#include <iostream>
using namespace std;
void decToOctal( int n)
{
int octalNum[100];
int i = 0;
while (n != 0) {
octalNum[i] = n % 8;
n = n / 8;
i++;
}
for ( int j = i - 1; j >= 0; j--)
cout << octalNum[j];
}
int main()
{
int n = 33;
decToOctal(n);
return 0;
}
|
Explanation
If the given decimal number is 33.
- Step 1: Remainder when 33 is divided by 8 is 1. Therefore, arr[0] = 1.
- Step 2: Divide 33 by 8. The new number is 33/8 = 4.
- Step 3: Remainder, when 4 is divided by 8, is 4. Therefore, arr[1] = 4.
- Step 4: Divide 4 by 8. The new number is 4/8 = 0.
- Step 5: Since the number becomes = 0.
Stop repeating steps and print the array in reverse order. Therefore, the equivalent octal number is 41.
Complexity Analysis
- Time Complexity: O(log N)
- Space Complexity: O(N), since creating an array to store octal numbers.
Refer to the complete article Program for Decimal to Octal Conversion for more methods to convert Decimal numbers to Octal numbers.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...