Open In App

C++ Program For Decimal To Octal Conversion

Last Updated : 03 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++

  1. Create an array to store the octal representation.
  2. Run a loop till the number is not zero.
  3. Extract the remainder by taking the mod of the number by 8 and store the remainder in the array as an octal digit.
  4. Update the number by dividing it by 8 in each iteration.
  5. Print the array in reverse order.

The below diagram shows an example of converting the decimal number 33 to an equivalent octal number.  

decimal to octal conversion in C++

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;
}


Output

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads