Write a program in C++ to convert a binary number to octal.
Flowchart of a binary number to octal number conversion
C++ Source Code of a binary number to octal number conversion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include<iostream> using namespace std; int main() { int i,j=1,binn,oct=0; cout<<"Enter a binary number: "; cin>>binn; do { i=binn%2; oct=oct+i*j; j=j*2; binn=binn/8; } while(binn>0); cout<<"Binary to octal "<<oct; } |
Excercise
Find the possible mistakes in the following Shamil’s Flow Table of the program to convert a binary number to octal.
Loop |
Condition |
What line will
execute?
|
Actual
Work |
1Time
J=4 4>0 |
true |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15,16 | J=n,n=4,1,binn=0
Binn=0+(4%2)*1=0 I=1*8=8 n=4/2=2 |
2Time
J=4 J=j/2=4/2 J=2 2>0 |
true |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15,16,17, 10, 11, 12, 13, 14, 15, 16 | Binn=0+(2%2)*8=0
I=8*8=64 n=2/2=1 |
3Time
J=2 J=2/2 J=1 1>0 |
true |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15, 16, 17, 10, 11, 12, 13, 14, 15,16,17,10,11,,12,13, 14,15,16 | Binn=0+(1%2)*64=
64 I=64*8=512 N=1/2=0 |
4Time
J=1 J=1/2 J=0 0>0 |
False |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,151617, 10, 11, 12, 13, 14, 15,16, 17, 10, 11, 12,13, 14, 15,16,17,18
19 |
Print binary=64 |