A directory of Objective Type Questions covering all the Computer Science subjects.
Here you can access and discuss Multiple choice questions and answers for various competitive exams and interviews.

This program takes a binary number as input and converts it to octal. Octal numbers have the base as 8.

C program to convert an binary number to octal - Source code

/* C Program to Convert Binary to Octal */
#include <stdio.h>
int main()
{
long int binary_num, octal_num = 0, j = 1, rem;
printf("Enter the binary number: ");
scanf("%ld", &binary_num);
while (binary_num != 0)
{
rem = binary_num % 10;
binary_num = binary_num / 10;
octal_num = octal_num + rem * j;
j = j * 2;
}
printf("Equivalent octal value: %lo", octal_num);
return 0;
}

Program Output

Enter the binary number: 10101101
Equivalent octal value: 255

Program Explanation

1. Take a binary number as input and store it in the variable binary_num.
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 octal_num with this value.
4. Increment the variable j by multiplying it with 2 and override the variable binary_num with the quotient obtained.
5. Repeat the steps 2-4 until the variable binary_num becomes zero.
6. Print the variable octal_num as output.