Program for Octal to Binary Number

Octal to Binary Number

We will write a C program to display the conversion of octal number to binary number and the number will be entered by the user. This will help to understand the basic structure of programming. In this program , we will display the coversion of octal number to binary number easily by using proper syntax and algorithms.

Program for Octal to Binary Number

Working of Program :

In the program, we will require some numbers from the user to display the conversion of octal number to binary number.

Important Note :

  • If the number is expressed by base 8 numeral system then that number is octal number.
  • If the number is expressed by base 2 numeral system then that number is binary number.

Syntax for while() loop:

while(condition)
{
    // Statements
    // Increment / Decrement
}

Problem 1

Write a program to convert the octal number into binary number using while loop.

  • Firstly, we have to enter the number.
  • Then print the number.

Code

Run
#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 number = %lld in binary number", oct, convert (oct));
  return 0;
}
long long convert (int oct)
{
  int dec = 0, i = 0;
  long long bin = 0;

  while (oct != 0)
    {
      dec += (oct % 10) * pow (8, i);
      ++i;
      oct /= 10;
    }
  i = 1;
  while (dec != 0)
    {
      bin += (dec % 2) * i;
      dec /= 2;
      i *= 10;
    }
  return bin;
}

Output

Enter an octal number = 789
789 in octal number = 1000001001 in binary number

Problem 2

Write a program to convert the octal number into binary number using function.

  • Firstly, we have to enter the number.
  • Then print the number.

Code

Run
#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 octal Number = ");
  scanf ("%d", &octal);
  printf ("Binary number = %ld\n", octalToBinary (octal));
}

Output

Enter the octal Number = 56
Binary number = 101110

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription