# Program to convert binary to octal using while loop

### 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

### 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

### 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

### 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)

Input/Output:
Enter a binary number:
101
octal value:  5