C++ Program to Convert Decimal Number To Octal Number
C++
// C++ program to convert a decimal // number to octal number #include <iostream> using namespace std; // Function to convert decimal // to octal void decToOctal( int n) { // Array to store octal number int octalNum[100]; // Counter for octal number array int i = 0; while (n != 0) { // Storing remainder in octal array octalNum[i] = n % 8; n = n / 8; i++; } // Printing octal number array in // reverse order for ( int j = i - 1; j >= 0; j--) cout << octalNum[j]; } // Driver Code int main() { int n = 33; // Function Call decToOctal(n); return 0; } |
41
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.
C++ Program For Decimal To Octal Conversion
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.