Problem statement:- Program to convert binary to octal using while loop.
Data requirement:-
Input Data:- binary
Output Data:-octal
Output Data:-octal
Program in C
Here is the source code of the C Program to convert binary to octal using a while loop.
Code:
Code:
#include<stdio.h>
#include<math.h>
int
main ()
{
int binary;
printf ("Enter a binary number: ");
scanf ("%d", &binary);
int octal = 0, decimal = 0, i = 0;
while (binary != 0)
{
decimal = decimal + (binary % 10) * pow (2, i);
i++;
binary = binary / 10;
}
i = 1;
while (decimal != 0)
{
octal = octal + (decimal % 8) * i;
decimal = decimal / 8;
i = i * 10;
}
printf ("octal value: %d",octal);
}
Input/Output:
Enter a binary number: 10001
octal value: 21
Program in C++
Here is the source code of the C++ Program to convert binary to octal using a while loop.
Code:
Code:
#include<iostream>
#include<cmath>
using namespace std;
int
main ()
{
int binary;
cout<<"Enter a binary number: ";
cin>>binary;
int octal = 0, decimal = 0, i = 0;
while (binary != 0)
{
decimal = decimal + (binary % 10) * pow (2, i);
i++;
binary = binary / 10;
}
i = 1;
while (decimal != 0)
{
octal = octal + (decimal % 8) * i;
decimal = decimal / 8;
i = i * 10;
}
cout<<"octal value: "<<octal;
}
Input/Output:
Enter a binary number: 1110101
octal value: 165
Program in Java
Here is the source code of the Java Program to convert binary to octal using a while loop.
Code:
Code:
import java.util.Scanner;
public class BinaryToOctal {
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
System.out.println("Enter a binary number: ");
int binary=cs.nextInt();
int octal = 0, decimal = 0, i = 0;
while (binary != 0)
{
decimal = (int) (decimal + (binary % 10) * Math.pow (2, i));
i++;
binary = binary / 10;
}
i = 1;
while (decimal != 0)
{
octal = octal + (decimal % 8) * i;
decimal = decimal / 8;
i = i * 10;
}
System.out.println("octal value: "+octal);
cs.close();
}
}
Input/Output:
Enter a binary number:
00010111
octal value: 27
Program in Python
Here is the source code of the Python Program to convert binary to octal using a while loop.
Code:
Code:
print("Enter a binary number: ")
binary=int(input());
octal = 0
decimal = 0
i = 0
while (binary != 0):
decimal = decimal + (binary % 10) * pow (2, i)
i+=1
binary = binary // 10
i = 1
while (decimal != 0):
octal = octal + (decimal % 8) * i
decimal = decimal // 8
i = i * 10
print("octal value: ",octal)
octal = 0
decimal = 0
i = 0
while (binary != 0):
decimal = decimal + (binary % 10) * pow (2, i)
i+=1
binary = binary // 10
i = 1
while (decimal != 0):
octal = octal + (decimal % 8) * i
decimal = decimal // 8
i = i * 10
print("octal value: ",octal)
Input/Output:
Enter a binary number:
101
octal value: 5
Most Recommend Questions:-
More Questions:-
0 Comments
Please do not Enter any spam link in the comment box