C Programs to Convert Binary to Octal

In this tutorial, i am going to show you how to convert binary number to Octal number in c program with the help of for loop, while loop and function.

All C Programs to Convert Binary to Octal

  • C Program to Convert Binary to Octal using While Loop
  • C Program to Convert Binary to Octal using For Loop
  • C Program to Convert Binary to Octal using Function

C Program to Convert Binary to Octal using While Loop

#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);
}

The result of the above c program; as follows:

Enter the Binary Number = 121010
The octal Value = 112

C Program to Convert Binary to Octal using 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); 
}

The result of the above c program; as follows:

Enter the Binary Number = 1101410
The octal Value = 172

C Program to Convert Binary to Octal using Function

#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;
}

The result of the above c program; as follows:

Enter the Binary Number = 11011011
The octal Value = 333

Be First to Comment

Leave a Reply

Your email address will not be published.