CPP Program convert decimal to octal

 In this example, you will learn about the conversion of decimal to octal number in the CPP programming language.

For understanding the program you have the knowledge about the following topic.

while loop

input method

output method


Code:

#include <iostream>

#include <cmath>

using namespace std;


int main()

{

   int decimalNumber,original;

   cout << "Enter a decimal number ";

   cin >> decimalNumber;


  original=decimalNumber;


    int remainder, i = 1, octalNumber = 0;


    while (decimalNumber != 0)

    {

        remainder = decimalNumber % 8;

        decimalNumber /= 8;

        octalNumber += remainder * i;

        i *= 10;

    }

     

     cout << original << " in decimal  =  " << octalNumber << "  in octal "<<endl;

   return 0;

}


Output:

Enter a decimal number 6789
6789 in decimal  =  15205  in octal

In the above code, while loop is used to convert the decimal number, separate the number by modulus 8, divide by 8 to decrease the one digit, and multiple by the power of 10 with unit place by using a power function. At the end of the loop, add in the decimal number. In this way, loop iterate in order to convert the whole number.

if you have any problem understanding the above code then write your query in the below comment section.


Comments

Popular posts from this blog

Diferrence between flutter and react native

Flutter Widgets

Flutter layout