belongs to collection: C programs - Basic C Programs
Writr C 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
#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.
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
C program to convert an binary number to octal - Source code
Program Output
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.
need an explanation for this answer? contact us directly to get an explanation for this answer