C Program to Convert Binary to Octal

«
»

This is a C program to Convert Binary to octal.

Problem Description

This program takes a binary number as input and converts to octal.

Problem Solution

1. Take a binary number as input.
2. Divide the binary number into groups of 3 bits. For each group of 3 bits, multiply each bit with the power of 2 and add them consecutively.
3. Combine the result of all groups to get the output.

Program/Source Code

Here is source code of the C program to Convert Binary to Octal. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Convert Binary to Octal
  3.  */
  4.  #include <stdio.h>
  5.  
  6. int main()
  7. {
  8.     long int binarynum, octalnum = 0, j = 1, remainder;
  9.  
  10.     printf("Enter the value for  binary number: ");
  11.     scanf("%ld", &binarynum);
  12.     while (binarynum != 0)
  13.     {
  14.         remainder = binarynum % 10;
  15.         octalnum = octalnum + remainder * j;
  16.         j = j * 2;
  17.         binarynum = binarynum / 10;
  18.     }
  19.     printf("Equivalent octal value: %lo", octalnum);
  20.     return 0;
  21. }
Program Explanation

1. Take a binary number as input and store it in the variable binarynum.
2. Obtain the remainder and quotient of the input number by dividing it by 10.
3. Multiply the obtained remainder with variable j and increment the variable octalnum with this value.
4. Increment the variable j by 2 and override the variable binarynum with the quotient obtained.
5. Repeat the steps 2-4 until the variable binarynum becomes zero.
6. Print the variable octalnum as output.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Runtime Test Cases
Output:
 
Enter the value for  binary number: 10101
Equivalent octal value: 25

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Simple C Programs, go to Simple C Programs. If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.