C Program to Convert Binary to Octal

Write a C program to convert binary to octal using a while loop. In this c example, the first while loop converts binary two decimal and the second loop converts a decimal to octal. 

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

int main()
{
    int i, octal = 0, decimal = 0;
    long binary;

    printf("Enter the Binary Number = ");
    scanf("%ld", &binary);
    
    i = 0;
    while(binary != 0)
    {
        decimal = decimal + (binary % 10) * pow(2, i);
        i++;
        binary = binary/10;
    }

    i = 1;
    while(decimal != 0) 
    {
        octal = octal + (decimal % 8) * i;
        decimal = decimal / 8;
        i = i * 10;
    }
    printf("The octal Value = %d\n", octal);
}
Enter the Binary Number = 10101011
The octal Value = 253

Enter the Binary Number = 10101
The octal Value = 25

This c program converts a binary number to octal using the for loop.

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

int main()
{
    int i, remainder, octal = 0, decimal = 0;
    long binary;

    printf("Enter the Binary Number = ");
    scanf("%ld", &binary);

    for(i = 1; binary != 0; i = i * 2, binary = binary / 10)
    {
        remainder = binary % 10;
        decimal = decimal + remainder * i;
    }

    for(i = 1; decimal != 0; i = i * 10) 
    {
        octal = octal + (decimal % 8) * i;
        decimal = decimal / 8;
    }
    printf("\nThe octal Value = %d\n", octal); 
}
C Program to Convert Binary to Octal 2

In this c example, the binaryTooctal function accepts the binary value, converts it to the octal number, and returns the same.

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

int binaryTooctal(long binary)
{
    int octal = 0, i, decimal = 0;

    for(i = 0; binary != 0; i++)
    {
        decimal = decimal + (binary % 10) * pow(2, i);
        binary = binary/10;
    }
    for(i = 1; decimal != 0; i = i * 10) 
    {
        octal = octal + (decimal % 8) * i;
        decimal = decimal / 8;
    }
    return octal;
}

int main()
{
    long binary;
    
    printf("Enter the Binary Number = ");
    scanf("%ld", &binary);

    printf("The octal Value = %d\n", binaryTooctal(binary)); 

    return 0;
}
Enter the Binary Number = 11011011
The octal Value = 333


Enter the Binary Number = 1011
The octal Value = 13