HomeC ProgrammingC Program to Convert Binary to Octal

C Program to Convert Binary to Octal

This C program converts a binary number to its octal equivalent.

Problem statement

The program takes a binary number as input and converts it into an octal number.

C Program to Convert Binary to Octal

#include <stdio.h>

int binaryToOctal(int binary) {
    int octal = 0, decimal = 0, base = 1;

    // Convert binary to decimal
    while (binary != 0) {
        int remainder = binary % 10;
        decimal += remainder * base;
        binary /= 10;
        base *= 2;
    }

    base = 1;

    // Convert decimal to octal
    while (decimal != 0) {
        int remainder = decimal % 8;
        octal += remainder * base;
        decimal /= 8;
        base *= 10;
    }

    return octal;
}

int main() {
    int binary;

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

    int octal = binaryToOctal(binary);

    printf("Octal equivalent: %d\n", octal);

    return 0;
}

How it works

  1. The program defines a function binaryToOctal() to convert binary to octal.
  2. The function takes the binary number as an argument and performs the conversion using the following steps:
    • First, it converts the binary number to its decimal equivalent by multiplying each digit with appropriate powers of 2.
    • Then, it converts the decimal number to octal by dividing it with 8 and building the octal number digit by digit.
  3. In the main() function, the user is prompted to enter a binary number.
  4. The entered binary number is passed to the binaryToOctal() function.
  5. The octal equivalent of the binary number is returned from the function and stored in the octal variable.
  6. Finally, the octal equivalent is printed on the console.

Input/Output

C Program to Convert Binary to Octal

Share:

Leave A Reply

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

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...