Friday, 20 June 2014

C++ program to convert decimal to octal


Here is a C++ program to convert decimal to octal. Here are the different methods to convert decimal to octal like using recursion, using manipulator etc.
How to convert decimal to octal (base 10 to base 8).
To convert decimal to octal a simple method is to continuously divide the number by 8 until final result is zero, in each division we get remainder, simply wrote the remainders starting from bottom to upwards .For example let us convert decimal number 16 to octal.
16 / 8  quotient = 2 ,rem = 0
2 / 8  quotient = 0 ,rem = 2
Thus octal equivalent of decimal number (16)10 is (20)8.


Method 1 : C++ program to convert decimal to octal
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    long octal=0,rem,num,temp=1;
    cout<<"Enter the number ";
    cin>>num;
    while(num>0)
    {
        rem=num%8;
        num/=8;
        octal=octal+rem*temp;
        temp*=10;
    }
    cout<<"Octal equivalent : "<<octal;
    return 0;
}



Method 2 : C++ program to convert decimal to octal using functions
#include<iostream>
using namespace std;
void oct(int);
int main()
{
    int n;
    cout<<"Enter number : ";
    cin>>n;
    cout<<"Octal equivalent : ";
    oct(n);
    return 0;
}
void oct(int n)
{
    int a[20],i;
    for(i=0;n!=0;i++)
    {
        a[i]=n%8;
        n=n/8;
    }
    for(int y=i-1;y>=0;y--)
        cout<<a[y];
}



Method 3 : C++ program to convert decimal to octal using recursion
#include<iostream>
using namespace std;
void octal(int n)
{
    if(n==0)
        return ;
    octal(n/8);
    cout<<n%8;
}
int main()
{
    int num;
    cout<<"Enter Decimal number : ";
    cin>>num;
    cout<<"Octal equivalent : ";
    octal(num);
    return 0;
}



Method 4 : C++ program to convert decimal number to octal using Manipulators
#include<iostream>
using namespace std;
int main()
{
    int n;
    cout<<"Enter number : ";
    cin>>n;
    cout<<"Octal equivalent : "<<oct<<n;
    return 0;
}




Method 5 : C++ program to convert decimal to octal and store it as string
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char a[20];
    int i,n;
    cout<<"Decimal equivalent : ";
    cin>>n;
    for(i=0;n>0;i++)
    {
        a[i]=n%8+48;
        n=n/8;
    }
    a[i]='\0';
    strrev(a);
    cout<<"Octal equivalent : "<<a;
}

No comments:

Post a Comment