C++ Program to Convert Binary to Octal

Write C++ Program to Convert Binary to Octal

// CPP Program to Convert Binary to Octal

#include <iostream>
#include <math.h>

using namespace std;

Binary_to_decimal(int n)
{
	int ans = 0, i = 0;
	while(n != 0)
	{
		int digit = n % 10;  //here we take the last digit
		if(digit == 1)
		{
			ans = (digit * pow(2,i)) + ans;	  //formula for the conversion
		}
		n = n / 10;				// reducing the number
		i++;
	}
	return ans;
}
int main()											
{
	int n;
	cout << "Enter the Binary Number :--> ";
	cin >> n;

	cout << "The Octal Number is :--> " << Binary_to_decimal(n);   
	return 0;
}

Output:

Enter the Binary Number :--> 101011
The Octal Number is :--> 53

≪ Previous | Next ≫