In this tutorial you will learn about the C Program to Convert Binary to Octal and its application with practical example.
C Program to Convert Binary to Octal
In this tutorial, we will learn to create a C program that will Convert Binary to Octal in C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
Program to Convert Binary to Octal:-
As we all know the c is a very powerful language. With the help of c programming language, we can make many programs. We cal perform many input-output operations using c programming. In today’s tutorial, we take the input in binary from the user and convert it into octal. With the help of c programming, we can perform many conversion operations.
With the help of this program, we can Convert Binary to Octal.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declare the variables for the program. 2. Takeing the input number from the user in binary for the program. 3. Passing that input to the string function. 4. Pass that number to a for loop for convertion. 4. Print the Result. 5. End the program. |
Program to Convert Binary to Octal:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <math.h> #include <stdio.h> int convert(long long bin); int main() { //declaring the variable for the program. long long bin; //taking the input from the user in binary number. printf("Enter a binary number: "); //scanning the input of binary number. scanf("%lld", &bin); //printing the binary to octal number printf("%lld in binary = %d in octal", bin, convert(bin)); return 0; } //function for the converting the binary to decimal and then to octal int convert(long long bin) { int oct = 0, dec = 0, i = 0; // converting binary to decimal while (bin != 0) { dec += (bin % 10) * pow(2, i); ++i; bin /= 10; } i = 1; // converting to decimal to octal while (dec != 0) { oct += (dec % 8) * i; dec /= 8; i *= 10; } return oct; } |
Output:-
In the above program, we have first initialized the required variable.
- bin = in will hold the integer value.
Taking the input.