Program to convert Decimal to Octal in C++

Here we will write a program to convert Decimal to Octal in C++ programming language. First lets start with how to convert any decimal number to an octal number:

Example:

Here is an example of using repeated division to convert 1792 from decimal number to an octal number:

Decimal Number  Operation  Quotient  Remainder  Octal Result
1792÷ 8 =22400
224÷ 8 =28000
28÷ 8 =34400
3÷ 8 =033400
0done.

Now let’s write the program to convert the same in C++ programming language.

Program to convert Decimal to Octal in C++:

#include<iostream>
using namespace std;

int main ()
{
int num,result[8]={0,0,0,0,0,0,0,0},flag=0;
cout<<"From Decimal: ";
cin>>num;
cout<<"\nTo Octal: ";

for(int i=0;i<8;++i)
    {
    result[7-i]=num%8;
    num=num/8;
    if(num==0)
    break;
    }
for(int i=0;i<8;++i)
    {
       if(result[i]!=0)
       flag=1;
       if(flag==1)
       cout<<result[i];
    }
return 0 ;
}

 

OUTPUT:

convert decimal to octal c

Leave a Comment