C Program to Convert Binary to Octal

C Program to Convert Binary to Octal

Write C Program to Convert Binary to Octal

// Write C Program to Convert Binary to Octal

#include <stdio.h>
#include <math.h>

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() //here first we convert Binary to Decimal and then decimal to octal
{
	int n;
	printf("Enter the Binary Number :--> ");
	scanf("%d", &n);

	printf("The Octal Number is :--> %o",Binary_to_decimal(n));   //easiest approach to find the octal number from the decimal
	return 0;
}

Output:

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