C++ Program for Decimal to octal conversion

Program for Decimal to octal conversion

The concept of conversion is very simple.A decimal number can be converted to an octal number by using the repeated division-by-8 method i.e repeatedly divide the decimal number by 8 until no further divisions can be done and the remainder of each division will give us the octal number of decimal number.

Example:717

1) 717/8, Remainder = 5, Quotient = 89 2) 89/8, Remainder = 1, Quotient = 11

3)  11/8, Remainder = 3, Quotient = 1    4)  1/8, Remainder = 1, Quotient = 0

717 in decimal = 1315 in octal.

Decimal to octal number

Algorithm:-

  1. User gives an input(decimal number).
  2. The input is stored in an int type variable say decimal.
  3. A function convert() is called with decimal as a parameter.
    1. A loop is started
      1. The number is divided by 8 and the remainder is stored.

                               int rem = decimal % 8;

                          2. The octal number is constructed using the remainder.

                              octal += rem * i;

               2. The loop will run until the number is not equal to 0.

                   while (decimal != 0)

      4. The output is printed

Decimal to octal conversion in C++

C++ Code:-

//C++ Program
//decimal to octal conversion
#include
#include using namespace std;
// Function to convert a decimal number to octal
int convert(int decimal)
{
int i = 1, octal = 0;
//converting decimal to octal
while (decimal != 0)
{
int rem = decimal % 8;
decimal /= 8;
octal += rem * i;
i *= 10;
}
return octal;
}
//main program
int main()
{
int decimal,octal;
cout << “Enter a decimal number: “;
//user input
cin >> decimal;
//calling function
octal = convert(decimal);
//printing output
cout << decimal << ” in decimal = “ << octal << ” in octal”;
return 0;
}
Output

Enter a decimal number: 1098

1098 in decimal = 2112 in octal
coding (3)