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 = | 224 | 0 | 0 | |
224 | ÷ 8 = | 28 | 0 | 00 | |
28 | ÷ 8 = | 3 | 4 | 400 | |
3 | ÷ 8 = | 0 | 3 | 3400 | |
0 | done. |
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 ; }