C program to Convert Octal to Binary

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

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

int main()
{
    int i, octal, decimal = 0;
    long binary = 0;
    i = 0;
    
    printf("Enter the Octal Number = ");
    scanf("%d",&octal);

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

    printf("The Binay Value = %ld\n", binary); 
}
C program to Convert Octal to Binary

In this c program, the octalToBinary function accepts the octal number and converts it to binary using the for loop.

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

long octalToBinary(int octal)
{
    int i, decimal = 0;
    long binary = 0;
    for (i = 0; octal != 0; i++)
    {
        decimal = decimal + (octal % 10) * pow(8, i);
        octal = octal / 10;
    }

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

int main()
{
    int octal;

    printf("Enter the Number = ");
    scanf("%d", &octal);

    printf("Result = %ld\n", octalToBinary(octal));
}
Enter the Number = 98
Result = 1010000


Enter the Number = 243
Result = 10100011

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.