C Programming

Solved Example

Practice Questions

Exercise Question

Program to find binary equivalent of a number

Objective

Write a program to find the binary equivalent of a number.

Program / Solution

#includestdio.h
#includemath.h
int main() {
	int i,n,dig,old;
        long bin;
	
	printf("Enter any number: ");
	scanf("%d",&n);
	
	i = 0; bin = 0; old = n;
	while(n != 0) {
		dig = n % 2; // find the octal digit
		n = n / 2; //divide the number
		bin = bin + dig * pow(10,i); //suffix digit in oct in reverse order
		i++;
	}
	
	printf("Binary equivalent %d = %ld",old,bin);
	return 0;
}

Sample Output

Enter any number: 50
Binary equivalent 50 = 10011