This program will accept input from the user as a binary number and convert that number into an octal number. To correctly understand this program, you should be familiar with the while loop concept.

Convert Binary to Octal using C

Here is the program source code to convert the binary number into octal. This program is successfully compiled, and the output is also given below.

#include <stdio.h>
 
int main()
{
    long int binNumber;
 
    printf("Please enter a binary number to convet it to octal: ");
    scanf("%ld", &binNumber);
    
    long int octNumber = 0;
    long int i = 1;
    long int rem;
    
    while (binNumber != 0)
    {
        rem = binNumber % 10;
        octNumber = octNumber + rem * i;
        i = i * 2;
        binNumber = binNumber / 10;
    }
    
    printf("Octal number is : %lo", octNumber);
    
    return 0;
}

Output

Please enter a binary number to convert it to octal: 10101010101

Octal number is: 2525

…Program finished with exit code 0

Press ENTER to exit console.

Program Explanation

Program start execution forms the main method. We declared a variable binNumber to read a binary value form the user. Later on, we declared three more variable named k, rem, and octNumber.

Inside while loop, we get the remainder by dividing the user entered number by 10 and store it into rem variable. After that multiplied the rem variable with the value of k and sum it with the value of an octNumber variable and save back into the octNumber variable.

Increment the k variable by 2 and override the value of binNumber variable after divided by 10. Repeat while loop until the value of binNumber becomes 0. If the condition of while loop becomes false, program prints the octNumber variable value as an output which will be the converted octal number.

Related articles

Last modified: April 26, 2019