Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator
conversion

How to convert a number from a decimal to an octal in C++

Vinisha Maheshwari

In this shot, we will discuss how to convert a number from decimal to octal in C++.

When we convert a decimal number to an octal number, we divide the number by 88. Then, we again divide the quotient by 88. We repeat the process until the remainder comes between 00 - 77.

Look at the image below to better understand how this conversion works.

Conversion of Decimal number to Octal number

In the above image, the number is divided by 88 until the remainder comes between 00 - 77. When the remainder is between 00 - 77, we write the values in reverse order, as shown in the image. For example, the value of a decimal number 333333 in octal form is 515515.

Let’s look at the following code snippet to understand it better.

#include <iostream>

using namespace std;

int main() {
  int decimal, octal = 0, remainder, product = 1;
  cin >> decimal;
  while (decimal != 0) {
    remainder = decimal % 8;
    decimal = decimal / 8;
    octal = octal + (remainder*product);
    product *= 10;
    }
  cout << "The number in the octal form is: " <<octal;
  return 0;
}

Enter the input below

Conversion of Decimal number to octal number in C++

Explanation

Enter a number in the above input section.

  • In line 6, we initialize the variables decimal, octal, remainder, and product.

  • In line 7, we take decimal as input.

  • From lines 8 to 12, we initialize a while loop. In the loop, we calculate the remainders and quotients as shown in the above illustration to convert the decimal number to its octal equivalent.

  • In line 14, we print the output, i.e., the octal equivalent of the decimal number.

This way, we can convert the value of a decimal number to an octal number.

RELATED TAGS

c++
communitycreator
conversion
RELATED COURSES

View all Courses

Keep Exploring