1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <conio.h> using namespace std; int main() { int num; int array[10],k=0; int n; cout<<"enter any number which is greater than 0:"; cin>>num; while(num>0) { array[k]=num%2; num=num/2; k++; } cout<<"output in form of binary number is:"; for(n=k-1;n>=0;n--) { cout<<array[n]; } } |
Output
enter any number which is greater than 0: 3
output in form of the binary number is: 11







Write a program in C++ to convert a decimal number into binary without using an array.
INTEGER PART | QUOTIENT | REMAINDER | REMAINDER IN QUOTIENT |
4/2 | 2 | 0 | 0 |
2/2 | 1 | 0 | 0 |
1/2 | 0 | 1 | 1 |
(4)10 = (100)2
Flowchart of decimal number into binary without using an array

C++ code of decimal number into binary using do-while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> using namespace std; int main() { int i,j,n,binaryn=0,decimaln=n; cout<<"enter decimal no:"; cin>>n; i=1; j=n; do { binaryn=binaryn+(n%2)*i; i=i*10; n=n/2; j=j/2; } while(j>0); cout<<"the binary no is:"<<binaryn; } |
Output
enter decimal no: 7
the binary no is: 11
Exercise
Find the possible mistakes in the following Shamil’s Flow Table of the program of decimal number into binary using a do-while loop.
Loop
|
Condition | What lines will execute | Actual work
|
1 time
J=4 4>0
|
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
|
J=n,n=4,i=1,bin=0
Bin=0+(4%2)*1=0 i=1*10=10 n=4/2=2 |
|
2 time
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
|
Bin=0+(2%2)*10=0
i=10*10=100 n=2/2=1
|
3 time
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
|
Bin=0+(1%2)*100=100
i=100*10=1000 n=1/2=0
|
4 time
J=1 J=1/2 J=0 0>0
|
False
|
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,18, 19
|
Print binary =100 |
C++ code of decimal number into binary using while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> using namespace std; int main() { int n, i, j, binary=0,num; cout<<"Convert Decimal to Binary:"<<endl; cout<<"-------------------------"<<endl; cout<<"Enter a number : "; cin>>n; num=n; i=1; j=n; while(j>0) { binary=binary+(n%2)*i; i=i*10; n=n/2; j=j/2; } cout<<"The Binary of "<<num<<" is = "<<binary; } |
Decimal number into binary using for loop in C++
Write a program in C++ to convert a decimal number into a binary number using for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> using namespace std; int main() { int T4Tutorials[10], n, i; cout<<"Please Enter the number to convert: "; cin>>n; for(i=0; n>0; i++) { T4Tutorials[i]=n%2; n= n/2; } cout<<"Binary of the given number= "; for(i=i-1 ;i>=0 ;i--) { cout<<T4Tutorials[i]; } } |
Output
Please Enter the number to convert: 8
Binary of the given number= 1000