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 $8$. Then, we again divide the quotient by $8$. We repeat the process until the remainder comes between $0$ - $7$.

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 $8$ until the remainder comes between $0$ - $7$. When the remainder is between $0$ - $7$, we write the values in reverse order, as shown in the image. For example, the value of a decimal number $333$ in octal form is $515$.

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

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 