Write a program in C++ to convert a binary number to octal

#include <iostream>
using namespace std;
void main()
{

int n1, n,p=1;
int dec=0,i=1,j,d;
        int ocno=0,dn;
     cout<<"Convert Binary to Octal:\n ";
cout<<"Input a binary number :";
cin>>n;
n1=n;
for (j=n;j>0;j=j/10)
{
          d = j % 10;
            if(i==1)
                  p=p*1;
            else
                 p=p*2;
  dec=dec+(d*p);
  i++;
}
     dn=dec;
     i=1;
      for(j=dec;j>0;j=j/8)
       {
        ocno=ocno+(j % 8)*i;
        i=i*10;
        n=n/8;
       }
        cout<<"\nThe Binary Number : "<<n1<<"\nThe equivalent Octal  Number : "<<ocno<<endl;
         system ("pause");
}


Test Data :
Input a binary number :1001
Expected Output :
The Binary Number : 1001
The equivalent Octal Number : 11

Write a program in C++ to convert a binary number to octal Write a program in C++ to convert a binary number to octal Reviewed by Unknown on June 20, 2017 Rating: 5

No comments:

Powered by Blogger.