# (C programming Example for Beginners)

# C Program to Convert Binary Number to Octal and vice-versa

#### In this example, you will learn to convert binary numbers to octal and vice versa manually by creating a user-defined function.

## Program to Convert Binary to Octal

In this program, we will first convert a binary number to decimal. Then, the decimal number is converted to octal.

```
#include <math.h>
#include <stdio.h>
int convert(long long bin);
int main(){
long long bin;
printf("Enter a binary number: ");
scanf("%lld", &bin);
printf("%lld in binary = %d in octal", bin, convert(bin));
return 0;
}
int convert(long long bin){
int oct = 0, dec = 0, i = 0;
// converting binary to decimal
while (bin != 0) {
dec += (bin % 10) * pow(2, i);
++i;
bin /= 10;
}
i = 1;
// converting to decimal to octal
while (dec != 0) {
oct += (dec % 8) * i;
dec /= 8;
i *= 10;
}
return oct;
}
```

**Output**

Enter a binary number: 101001 101001 in binary = 51 in octal

## Program to Convert Octal to Binary

In this program, an octal number is converted to decimal at first. Then, the decimal number is converted to binary number.

```
#include <math.h>
#include <stdio.h>
long long convert(int oct);
int main(){
int oct;
printf("Enter an octal number: ");
scanf("%d", &oct);
printf("%d in octal = %lld in binary", oct, convert(oct));
return 0;
}
long long convert(int oct){
int dec = 0, i = 0;
long long bin = 0;
// converting octal to decimal
while (oct != 0) {
dec += (oct % 10) * pow(8, i);
++i;
oct /= 10;
}
i = 1;
// converting decimal to binary
while (dec != 0) {
bin += (dec % 2) * i;
dec /= 2;
i *= 10;
}
return bin;
}
```

**Output**

Enter an octal number: 67 67 in octal = 110111 in binary

## C Example for Beginners: C Program to Convert Binary Number to Octal and vice-versa

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause.The information presented here could also be found in public knowledge domains.