SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
C Program to convert decimal to binary
C Program to convert decimal to binary
Input:
5
Output:
000000000000101
Method 1:
#include
#include
int main(void) { int n; int i; /* get the number to find its binary */ scanf("%d",&n); /* 100000000000000 will bitwise and with 000000000000101 , so we get 1's when 101 left shifted */ for(i=1;i<=15;i++) printf("%d",1<<15 & n<
Method 2:
#include
/* recursive function */ void binary(int n) { /* conditional recursive call Call recursively until n becomes 1 or lesser than 1 */ if(n>1) binary(n/2); /* until then print the reverse of the recursive data processed */ printf("%d",n%2); } int main(void) { int n; /* get the input number to print its binary */ scanf("%d",&n); /* call the recursive function binary to print binary of n */ binary(n); return 0; }
Method 2.1:
(Print the binary in reverse)
#include
int main(void) { int n; /* get the input number from the user*/ scanf("%d",&n); /* print the binary result & divide n by 2 every time, till n is a true value */ for(;n;printf("%d",n%2),n/=2); return 0; }
Method 2.2:
#include
/* recursive function to convert number to binary */ void tobinary(int n) { /* condition to break the recursive loop */ if(n==0) return; /* call the tobinary function recursively */ tobinary(n/2); /* print the binary representation of the number entered by the user */ printf("%d",n%2); } int main(void) { int n; /* get the number from the user */ scanf("%d",&n); /* call the recursive function to print the binary of number n */ tobinary(n); return 0; }
PREVIOUS
NEXT
HOME