# C Program To Convert Binary To Octal

In this post, we will learn how to convert binary to octal using C Programming language.

This program will take a binary number as input from the user and convert it into an octal number using a user-defined function.

So, without further ado, let’s begin this tutorial.

## C Program To Convert Binary To Octal

```// C Program To Convert Binary To Octal
#include <stdio.h>
#include <math.h>

int binaryToOctal(long num){
int octal = 0, decimal = 0, i = 0;

while (num != 0){
decimal = decimal + (num % 10) * pow(2, i);
i++;
num = num / 10;
}

i = 1;
while (decimal != 0){
octal = octal + (decimal % 8) * i;
decimal = decimal / 8;
i = i * 10;
}
return octal;
}

int main(){
long num;

printf("Enter a binary number: ");
scanf("%ld", &num);

printf("Equivalent Octal Number is: %d", binaryToOctal(num));
return 0;
}
```

Output

``````Enter a binary number: 10010
Equivalent Octal Number is: 22
``````

## How Does This Program Work ?

``````    long num;
``````

In this program, we have declared a long int data type variable named as num.

``````    // Asking for Input
printf("Enter a binary number: ");
scanf("%ld", &num);
``````

Then, the user is asked to enter a binary number. The value of this binary number will get stored in the num named variable.

`````` printf("Equivalent Octal Number is: %d", binaryToOctal(num));
``````

Now, we call our user defined function named binaryToOctal which converts a binary number into an octal number and returns an octal number.

``````int binaryToOctal(long num){
int octal = 0, decimal = 0, i = 0;

while (num != 0){
decimal = decimal + (num % 10) * pow(2, i);
i++;
num = num / 10;
}

i = 1;
while (decimal != 0){
octal = octal + (decimal % 8) * i;
decimal = decimal / 8;
i = i * 10;
}
return octal;
}
``````

We have defined a custom function named binaryToOctal. This function first converts the binary number into a decimal number, and then converts the decimal number into an octal number.

## Conclusion

I hope after going through this post, you understand how to convert binary into octal using C Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.