C program that takes a non- negative integer number as input and prints its binary representation
Posted by Samath
Last Updated: January 01, 2017

Write a C program that takes a non- negative integer number as input and prints its binary representation.

Code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int nose=1; //initializing variables and matrix
	int inputnumber;
	int binaryoutput[8]; //Range of unsigned values: 0 - 255
	int i;
	int n;
	printf("Enter the desired integer to be converted to binary (enter -1 to finish)\n");

	scanf("%d", &inputnumber); //User input
	while( inputnumber != -1 ) //While loop to input different numbers at one's own convenience
	{
		if(inputnumber < 256 && inputnumber >= 0) //restrictions taken from the Range of values possible
		{
			for( i = 0; i < 8; i++ )
			{
				n = inputnumber % 2;
				if( inputnumber == 0 )
				{
					binaryoutput[i]=0;
				}
				else
				{
					binaryoutput[i]=n;
				}
				inputnumber = inputnumber / 2;
			}
		}
		else
		{
			printf("\nNumber out of boundary please re-enter to end -1\n"); //Wrong input gives a chance to repeat.
		}
	printf("\nThe binary representation is:\n%d%d%d%d%d%d%d%d\n",binaryoutput[7],binaryoutput[6],binaryoutput[5],binaryoutput[4],binaryoutput[3],binaryoutput[2],binaryoutput[1],binaryoutput[0] );
	printf("\nEnter the desired integer to be converted to binary\n");
	scanf("%d", &inputnumber);
}
system("PAUSE");
return 0;
}