BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C Program to Convert Binary to Octal Number System

By Chaitanya Singh | Filed Under: C Programs

This C Program converts a binary number to an equivalent octal number.

Example: Program to convert Binary to Octal

In this program, user is asked to enter the binary number and the program then converts that binary number to the octal number by calling a user defined function. To understand this program, you should be familiar with the following C programming concepts:

  1. C – while loop
  2. C – Functions
#include <stdio.h>
#include <math.h>
//This function converts binary number to octal number
int binaryToOctal(long binarynum)
{
    int octalnum = 0, decimalnum = 0, i = 0;

    /* This while loop converts binary number "binarynum" to the
     * decimal number "decimalnum"
     */
    while(binarynum != 0)
    {
        decimalnum = decimalnum + (binarynum%10) * pow(2,i);
        i++;
        binarynum = binarynum / 10;
    }

    //i is re-initialized
    i = 1;

    /* This loop converts the decimal number "decimalnum" to the octal
     * number "octalnum"
     */
    while (decimalnum != 0)
    {
        octalnum = octalnum + (decimalnum % 8) * i;
        decimalnum = decimalnum / 8;
        i = i * 10;
    }

    //Returning the octal number that we got from binary number
    return octalnum;
}
int main()
{
    long binarynum;

    printf("Enter a binary number: ");
    scanf("%ld", &binarynum);

    // calling the function here
    printf("Equivalent octal value: %d", binaryToOctal(binarynum));

    return 0;
}

Output:

Enter a binary number: 111001
Equivalent octal value: 71

In this program, we are converting the entered binary number to decimal number first and then we are converting that decimal number to the octal number.

Check out these related C programs:

  1. C Program to convert binary to decimal
  2. C Program to convert decimal number to binary
  3. C Program to convert Octal number to Binary
  4. C Program to convert lowercase string to uppercase
  5. C Program to convert uppercase string to lowercase

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Programs

  • C Programs
  • Java Programs
  • C++ Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap