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 . Then, we again divide the quotient by . We repeat the process until the remainder comes between - .
Look at the image below to better understand how this conversion works.
In the above image, the number is divided by until the remainder comes between - . When the remainder is between - , we write the values in reverse order, as shown in the image. For example, the value of a decimal number in octal form is .
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
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
CONTRIBUTOR
View all Courses