You are on page 1of 1

/* c program to input binary number and count number of 1 and 0s*/

#include <stdio.h>
#include <string.h>//we will use string to store the binary input from the user as
we do not have a data type to accept the binary input
#include <stdlib.h>
int bin_verify(char []);//to check if it is a valid binary number
void count();//to count 0 and 1
int check,zeros = 0,ones = 0;
char bin1[33];
int main()
{
printf("Enter binary number : ");
scanf("%s", bin1);
check = bin_verify(bin1);
if (check)
{
printf("Invalid binary number %s.\n", bin1);
exit(0);
}
else
{
count();
}
}
int bin_verify(char str[])
{
int i;

for (i = 0; i < strlen(str); i++)


{
if ((str[i] - '0' != 1 ) && (str[i] - '0' != 0))
{
return 1;
}
}
return 0;
}
void count()
{
int i = strlen(bin1)
for(int j=0;j<=i;j++)
{
if(bin1[i]== '1')
{
ones++;
}
else
{
zeros++;
}
printf("entered binary number is : %s\n",bin1);
printf("number of 0 is : %d\n",zeros);
printf("number of ones are : %d\n",ones);
}

You might also like